【发布时间】:2022-01-11 09:18:22
【问题描述】:
我正在尝试 malloc 结构 customerInformation。但是,我不断收到“错误:从类型‘void *’分配给类型‘struct CustomerInformation’时不兼容的类型”。我的声明中缺少什么?任何帮助,将不胜感激。谢谢。
struct CustomerInformation *result=malloc(sizeof(struct CustomerInformation)*100000);
for(int i=0;i<n;i++)
{
result[i]=malloc(sizeof(struct CustomerInformation));
}
【问题讨论】:
-
那是因为
result[i]存储了一个值,但是malloc返回了一个指针void * -
您已经为 100000
struct CustomerInformation分配了内存。然后没有必要尝试分配每个单独的结构,除非您的结构很大并且您需要在主数组中存储指针而不是值(在这种情况下,result的类型是错误的)。你在那个循环中应该做的是初始化每个元素的实际数据。