如何在c中初始化数组?

时间:2013-06-22 13:06:56

标签: c arrays

我已编写此代码但在编译时我收到消息“无效表达式” 以下陈述

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;
    }
}

3 个答案:

答案 0 :(得分:8)

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

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

可能之后会出现sizeof(address)的问题;如果你需要它,最好只使用另一个变量。

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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

如果从临时数组进行复制,最好将其设为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更改为指针并继续修改其指向的内容,则可能会产生意想不到的后果。

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

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; */
    }
}