gpt4 book ai didi

c - 使用 typedef 时如何分配内存?

转载 作者:行者123 更新时间:2023-11-30 21:44:13 24 4
gpt4 key购买 nike

我有一个类似这样的代码段

typedef struct node* node_t;

struct node{
int value;
node_t link;
};

......
......
......

//now I want to allocate memory somewhere else in the program.
node_t x;
x=(node_t) malloc(sizeof *x);

请问您的上述说法是否正确? Eclipse 显示此警告

warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
../tree.c:22:9:
warning: incompatible implicit declaration of built-in function ‘malloc’

有人可以详细解释一下这样的情况吗?这实际上有什么问题。如果您能列出我可以在此程序中分配内存的所有可能方式,我将不胜感激。提前谢谢您..

最佳答案

为了使用malloc您需要包括 <stdlib.h> 。此外,分配内存如

node_t x = malloc(sizeof node_t);

您不能将内存分配给堆栈变量,而只能分配给指针。并且永远不要转换回分配的类型,如 malloc返回void*并且这不需要显式转换。

关于c - 使用 typedef 时如何分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584589/

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