我正在尝试使用另一个指针将结构分配给指针
typedef struct cat Category;
Category{
///some stuff here
};
Category *categoryList;
Category *ap = &categoryList;
*ap = (Category *)malloc(sizeof(Category));
我明白了:
error: incompatible types when assigning to type 'Category' from type 'struct Category *'
我做错了什么?
最佳答案
您正在将指向结构类别的指针分配给指向结构类别的指针。是的,这是很多“tos”。那么如何解决呢?
typedef struct cat Category;
Category{
///some stuff here
};
// declare variable - pointer to category
Category *categoryList;
// store address of variable categoryList, which is pointer in variable ap,
// which needs to be of type Category ** since it is pointer to pointer!
Category **ap = &categoryList;
// assign pointer to mallocated address to categoryList whose address is
// accessed - dereferenced via *ap
*ap = malloc(sizeof(Category));
另请注意,您不应强制转换 malloc 的返回值。解释请引用this answer
关于C结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26382603/