typedef struct Expected {
const int number;
const char operand;
} Expected;
Expected array[1];
Expected e = {1, 'c'};
array[0] = e;
我不明白为什么不能像那样添加结构数组。我需要自己计算内存中的位置吗?
typedef struct Expected {
const int number;
const char operand;
} Expected;
Expected array[1];
Expected e = {1, 'c'};
array[0] = e;
我不明白为什么不能像那样添加结构数组。我需要自己计算内存中的位置吗?
Expected
元素被声明为const
,这意味着它们不能被修改。
为了设置值,需要在变量定义时进行初始化:
Expected array[1] = { {1, 'c'} };
在这种情况下,你使用的数组并不重要。
const
意味着您不能对它们进行写操作。移除这个限制后,代码可以正常工作。typedef struct Expected {
int number;
char operand;
} Expected;
不允许这样做是因为struct
有const
成员:
当一个结构体有一个const成员时,整个结构体也无法被赋值。error: assignment of read-only location
array[0]
array[0] = e;
Expected replacement = {.number = array[0].number, .operand = newOperand}; // << Allowed
array[0] = replacement; // <<== This is not allowed
const
,则必须使用初始化程序构建数组,而不能使用分配。