【问题标题】:Incompatible type from type void*与 void* 类型不兼容的类型
【发布时间】: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 的类型是错误的)。你在那个循环中应该做的是初始化每个元素的实际数据。

标签: c malloc


【解决方案1】:

result[i] 的类型为 struct CustomerInformation(不是指针),但您分配的是 void *(指针)。


如果你想要一个指向结构数组的指针:

struct CustomerInformation *result = malloc(sizeof(struct CustomerInformation*) * 100000);

for(int i=0;i<n;i++)
{
    result[i].cust_id = ...;
}

一大块内存,包含 100000 个 CustomerInformation 结构。


如果你想要一个指向结构指针数组的指针:

struct CustomerInformation **result = malloc(sizeof(struct CustomerInformation*) * 100000);

for(int i=0;i<n;i++)
{
    result[i] = malloc(sizeof(struct CustomerInformation));

    result[i]->cust_id = ...;
}

一大块内存包含 100000 个指针,加上 n 较小的每个包含一个 CustomerInformation 结构体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多