我创建了 10 x 10 数组的结构体来存储随机数。还制作了一个列表,因此每个成员将持有不同的 10 x 10。但是当我打印它时,数字有点坏,我不知道我的 for 循环是否不正确或还有其他东西。我希望我做的清单是正确的。
struct Num
{
int Numbers[10][10];
};
struct Hold
{
struct Num *List;
}FullList;
int main(void)
{
time_t t;
int x;
srand((unsigned) time(&t));
printf("Enter the number of arrays you want to create: ");
scanf("%d", &x);
FullList.List = malloc(x * sizeof(int));
if (FullList.List == NULL) {
fprintf(stderr, "Malloc failed.\n");
exit(1);
}
int i, j, k;
for(i=0;i<x;i++)
{
for(j=0;j<10;j++)
{
for(k=0;k<10;k++)
{
FullList.List[i].Numbers[j][k] = rand() % 255;
}
}
}
for(i=0;i<x;i++)
{
for(j=0;j<10;j++)
{
for(k=0;k<10;k++)
{
printf("%d %d %d %d %d %d %d %d %d %d \n", FullList.List[i].Numbers[j][k]);
}
}
}
return 0;
}
我将假设ImageList
是一个错字,而您的意思是FullList
,这就是我将在我的示例中使用的内容。如果是这种情况,那么您没有正确分配内存:
FullList.List = malloc(x * sizeof(int));
您为x
int
对象分配了足够的空间,而不是x
类型的对象struct Num
。你不分配的任何地方附近有足够的空间为您的使用目的。一个更好的方法是
FullList.List = malloc( x * sizeof *FullList.List )
该表达式sizeof *FullList.List
等效于sizeof (struct Num)
; 这将为x
struct Num
对象分配足够的空间,这正是您想要的。一般来说,你应该把你的malloc
电话写成
T *p = malloc( sizeof *p * N ); // for any non-function type T
要么
T *p = NULL;
...
p = malloc( sizeof *p * N );
经常检查的结果malloc
,calloc
和realloc
电话。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句