我想分配结构数组,但 GCC 出现此错误:
st.c: In function ‘main’:
st.c:20:4: error: incompatible types when assigning to type ‘struct employeeStruct’ from type ‘void *’ *sp=malloc(sizeof(struct productStruct)*n);
这是我的结构和指针:
struct productStruct
{
unsigned int ID;
unsigned long int serialnumber;
char name[40];
};
struct productStruct *sp;
在主函数中从用户那里获取 n 变量后:(我在这一行收到错误)
*sp=malloc(sizeof(struct *productStruct)*n);
我不知道这是否是类型转换错误,但我无法修复它。 感谢您的关注
最佳答案
您有 2 个错误:
使用 sp
而不是 *sp
并保留结构的大小,而不是指向结构的指针的大小(如果您确实想要一个结构数组而不是指针):
sp=malloc(sizeof(struct ProductStruct)*n);
关于c - 如何在 C 中使用 malloc() 分配结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49774138/