C结构指针

标签 c pointers struct

我正在尝试使用另一个指针将结构分配给指针

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/

相关文章:

c - 初始化带有数组的结构时出现段错误

c - 当结构体包含字符串时为其分配内存

c - 读取二进制文件时如何分别对每个结构体字段使用 fread() ?

c - 为什么 gets() 不起作用?

将包含二进制表示的字符串转换为数字 - C

c++ - 为什么声明 int* p1, p2; 中的 p2 不是指针类型?

c - 双字符指针 c 的简单多次重新分配

c++ - 为什么我的指针在我在 main 中取消引用它之后和在我自己的自定义函数中取消引用它时有不同的值?

Cygwin shell : $ make ex1 returns: "The system cannot find the specified file" on Windows 7

c - 查找数组中第三大的一对之和