【发布时间】:2013-04-20 04:01:42
【问题描述】:
我一直在尝试创建一个动态分配的结构类型 label 的数组,但失败得很惨。在我的 .h 文件中,我有:
typedef struct _label {
char name[256];
char type[256];
int address;
} label;
在我的 .c 文件中,我在顶部有这个:
label* allLabels = (label*) malloc(sizeof(label) * 10); // line 10
int arrayIndex = 0;
最后,我在同一个 .c 文件中有一个函数,用于将这些结构对象添加到数组中,以供文件中的其他方法使用:
void addLabel(char line[], char type[], int addr) {
label database;
database.name = line; // line 805
database.type = type; // line 806
database.address = addr;
allLabels[arrayIndex] = database;
arrayIndex++;
}
基本上我只想拥有一组可访问的标签。有人可以帮我理解我做错了什么吗?
我得到了这些错误,我也没有忘记任何必要的#include 语句:
formatBuilder.c:10:3: error: initializer element is not constant
formatBuilder.c: In function 'addLabel':
formatBuilder.c:805:18: error: incompatible types when assigning to type 'char[256]' from type 'char *'
formatBuilder.c:806.18: error: incompatible types when assigning to type 'char[256]' from type 'char *'
【问题讨论】:
-
数组不是指针。您不能使用
=运算符为数组分配新值。 -
代码中的
database是什么? -
database是我的标签对象的名称
标签: c arrays struct dynamic-allocation