0

我已经编写了这段代码,但在编译时,我收到以下语句的“无效表达式”消息

unsigned short address[] ={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/*array is being   initialized here.no problem uptil here.*/
unsigned short rowHead=3;
unsigned short colHead=0;
unsigned short rowTail =0;
unsigned short colTail =0;
unsigned short foodx;
unsigned short foody;
unsigned short turn=0;
void gameOver()
{
unsigned short i=0;
address[] ={0b10000001,0b01000010,0b00100100,0b00011000,
            0b00011000,0b00100100,0b01000010,0b10000001};
/*this is the line where compiler complaints as invalid expression.*/
while(1)
    {
    PORTD &=~(1<<i);
    PORTB =address[i];
    delay_ms(5);
    PORTD |=1<<i;
    i%8;
    }
}
4

3 回答 3

8

您只能在同时声明和分配变量时这样做。之后你不能这样做。但是,您可以创建另一个变量并分配它:

unsigned short address2[] = { 0b10000001,0b01000010,0b00100100,0b00011000,
                              0b00011000,0b00100100,0b01000010,0b10000001 };
address = address2;

可能会在之后产生问题sizeof(address);如果您需要,最好只使用另一个变量。

于 2013-06-22T13:08:45.370 回答
0

如果您想一次性分配整个数组(而不仅仅是获取对它的引用),您可以将其包装成 struct这样的:

#include <stdlib.h>
#include <stdio.h>

#define ADDRESS_DEF {1, 2, 3}

typedef struct 
{
  unsigned short _[sizeof((int[]) ADDRESS_DEF) / sizeof(*((int[]) ADDRESS_DEF))];
} address_t;

address_t address_def = {ADDRESS_DEF};

int main()
{
  address_t address = address_def;

  size_t size = sizeof(address._) / sizeof(*address._);

  for (size_t s = 0; s < size; ++s)
    printf("address #%zd = %uh\n", s, address._[s]);


  address = (address_t) {{4, 5, 6}};

  for (size_t s = 0; s < size; ++s)
    printf("address #%zd = %uh\n", s, address._[s]);

  return 0;
}
于 2013-06-22T14:41:01.327 回答
0

gameOver()函数中,您尝试使用单个赋值来分配数组的所有值。这是不合法的。您通常会使用memcpy()or 循环来一一设置值。这通常通过声明和初始化一个临时数组并将内容复制到要重新初始化的数组中来完成。

如果您确实从临时数组复制,最好的做法是制作它,staticconst通知编译器您并不是要写入它,并且您不需要在每次执行代码时都重新初始化它。像这样:

static const unsigned short tmp[] = { 0x81, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x81 };
memcpy(address, tmp, sizeof(address));

不过,您的目标变量的名称有点可疑。通常,如果某个东西被调用address,我希望它是一个指针。如果您的意思是它是一个指针,并且如果您不打算更改address指向的值,那么您的分配几乎是合法的。

unsigned short const *address;
/* ... */
static const unsigned short tmp[] = { 0x81, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x81 };
address = tmp;

制作tmp[]const(并制作address指向 const 的指针)允许编译器将数据放在只读段中,这可能意味着嵌入式系统上的 ROM。

如果您的代码存在一些隐藏的复杂性,而问题未显示,这会阻止您创建address指向 的指针const,那么事情就会变得复杂。如果您更改address为指针并继续修改它所指向的内容,这可能会产生意想不到的后果。

但是,显示的代码看起来不需要复制,并且元素不需要大于 achar来保存它们的所有值。临时数组可以很容易地成为工作数组:

void gameOver()
{
    unsigned short i=0;
    static const unsigned char tmp[] = { 0x81, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x81 };

    while(1)
    {
        PORTD &=~(1<<i);
        PORTB = tmp[i];
        delay_ms(5);
        PORTD |=1<<i;
        i%8;  /* <-- this has no effect, I think you meant i=(i+1)%8; */
    }
}
于 2013-06-22T19:02:12.083 回答