gpt4 book ai didi

C结构指针

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:11 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com