c - 通过双指针为结构分配内存
问题描述
嗨,我需要帮助来为属于第二个结构的结构分配内存,并且第二个结构具有双指针作为减速。
struct ant{
int stu;
int clas;
char *name;
};
struct cat{
int a;
int b;
struct ant *c;
};
int main()
{
struct cat **sample;
struct ant *info;
info = calloc(1, sizeof(*info));
<here i had allocated memory for **info** which is of type **ant**>
<now i need to assig this **info** to the pointer which is there in **cat** structure>
<how we can achive this> ?
}
解决方案
您的cat
结构有一个c
可以保存指向结构的指针的成员ant
。只需将指向您的ant
结构的指针分配给c
成员。如果你有一个指向结构的双指针cat
,你首先必须取消引用它。
struct cat *some_cat_p;
some_cat_p = calloc(1, sizeof(*some_cat_p));
struct cat **some_cat_pp;
some_cat_pp = &some_cat_p;
struct ant *some_ant_p;
some_ant_p = calloc(1, sizeof(*some_ant_p));
(*some_cat_pp)->c = some_ant_p;
注意:您可能还想检查 calloc 和朋友的返回值,NULL
如果分配内存失败,它可能会返回。
推荐阅读
- vue.js - 在 Carousel-Item 中对两个图像进行 Vuetify
- javascript - 在我当前的 Gmail API 项目中无限滚动 Gmail 消息
- r - 将日期和作者放在同一行,然后放在水平行 - YAML HEADER
- go - 将 *grpcpool.ClientConn 转换为 *grpc.ClientConn 的方法
- python - 如何使用numba并行?
- python - 按字符串列和 datetime64[ns] 列分组
- excel - 通过xmlhttp下载图片
- java - Kotlin/Java - 如何识别全角字符?
- javascript - 退出过程后机器人未重新启动
- sharepoint-online - 如何为单页 Web 部件添加菜单项?