C数据结构如何声明

时间:2013-10-25 16:23:41

标签: c data-structures struct

我坚持如何操纵数据结构。

我有头文件,声明像这样

struct item{
 int    i;  
 char   str[88];
};

我有一个 C 文件,我想制作9个结构项(我声明为全局变量,我已经包含了头文件):

struct item a[9];

但是当我想将我想要的数据放入

foo()

    {
    ...
      // let's say I have data int in index and char[] in string
      // and I want it to put at item_index

      a[item_index].i = index;
      a[item_index].str = string;
    ...
    }

但是当我尝试编译时,它似乎总是显示

error: expected an identifiler

2 个答案:

答案 0 :(得分:5)

a[item_index].str = string;

此行不会按照您期望的方式运行。您需要使用strcpy()才能复制字符串:

strcpy(a[item_index].str, string)

答案 1 :(得分:0)

Array Name是一个不可修改的(只读)变量,或者更好的说是常量。

在此声明中:

a[item_index].str = string;

您尝试修改数组str,这是不允许的。

您可以逐个为每个索引分配值(这是由strcpy完成的),
或者声明一个指针*str而不是数组,然后为它指定任何你想要的地址。