【发布时间】:2020-02-16 16:14:35
【问题描述】:
我正在复习一些 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);
【问题讨论】:
-
dataCollection是Collection**,但您将其视为Collection*。首先适当地命名您的类型和变量; “收藏”不是收藏记录的最佳名称(与收藏本身相反) -
dataCollection->age = 20;尝试取消引用dataCollection(此时它只不过是指向包含 10 个未初始化 指针 的内存块的指针。不会工作。 -
并且您在最后一个
for循环中有多个free(dataCollection)。你应该把它拿出来。线条在那里,但位置不正确:)
标签: c pointers struct dynamic-memory-allocation dataitem