![](/img/trans.png)
[英]Trying to declare an array of struct room inside of the room struct definition in C
[英]Trying to set a struct's inside array to be initialized in C
我有这个结构定义:
typedef struct intArray
{
int myArray[1000];
} intArray;
我的目标是创建一个零的intArray,我试过这个:
intArray example;
int createArray[1000] = {0};
example.myArray = createArray;
这会导致此错误消息:
error: assignment to expression with array type
我希望struct自动将数组初始化为0,但我知道这是不可能的,因为它只是一个类型定义而不是变量。 所以我创建了一个并创建了数组,只是尝试分配它,这就是结果。 任何建议表示赞赏。
声明像int myArray[1000];
这样的数组int myArray[1000];
不会让你改变数组指针的值。 声明你的结构
typedef struct intArray
{
int *myArray;
} intArray;
如果你可以的话。
为什么不使用memset将数组归零? 另外,正如另一个用户所建议的那样,最好将这个内存分配给指针....特别是如果你打算在函数之间传递这个结构。
只是一个想法,但这将工作:
typedef struct intArray {
int *myArray;
} intArray;
int main(void)
{
intArray a;
int b;
// malloc() and zero the array
//
// Heh...yeah, always check return value -- thanks,
// Bob__ - much obliged, sir.
//
if ((a.myArray = calloc(1000, sizeof *a.myArray)) == NULL) {
perror("malloc()");
exit(EXIT_FAILURE);
}
memset(a.myArray, 0, (1000 * sizeof(int)));
// Fill the array with some values
//
for (b = 0; b < 1000; b++)
a.myArray[b] = b;
// Just to make sure all is well...yep, this works.
//
for (b = 999; b >= 0; b--)
fprintf(stdout, "myArray[%i] = %i\n", b, a.myArray[b]);
free(a.myArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.