我正在复习一些 C 编程,并试图理解为什么在为结构动态分配内存后无法从结构 (struct) 打印数据项。
我尝试打印结构中的数据项以查看我得到的值,但我的代码无法编译,并且出现错误。
#include <stdio.h>
#include <stdlib.h>
typedef struct Collection {
int age;
char date[20];
char name[20];
} Collection;
int main(void) {
int i;
int n = 10;
Collection **dataCollection;
dataCollection = malloc(sizeof(Collection*)*n);
dataCollection->age = 20;
for(i = 0; i < n; i++) {
dataCollection[i] = malloc(sizeof(Collection)*n);
printf("Data collection item: %d\n", dataCollection->age);
}
for(i = 0; i < n; i++)
free(dataCollection[i]);
free(dataCollection);
return 0;
}
我收到以下错误:
practice1019.c:18:20: error: member reference base type 'Collection *' (aka 'struct Collection *')
is not a structure or union
dataCollection->age = 20;
~~~~~~~~~~~~~~^ ~~~
practice1019.c:23:56: error: member reference base type 'Collection *' (aka 'struct Collection *')
is not a structure or union
printf("Data collection item: %d\n", dataCollection->age);