如何在 C 中使用 malloc() 分配结构数组?
How can I allocate Array of Structure with malloc() in C?
我想分配结构数组,但我在使用 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);
我想分配结构数组,但我在使用 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);