是否可以像这样编写c malloc函数代码

Is it possible to write c malloc function code like this

本文关键字:malloc 函数 代码 像这样 是否      更新时间:2023-10-16

在堆上分配内存感到困惑?

如果我像这样编写以初始化堆内存中的变量

((struct node*)malloc(sizeof(struct node)).data=2

我可以这样写而不是使用指针吗? 如果我声明节点类型变量,那么是否可以这样编写或不这样做? 如果我不通过访问直接地址使用指针。

是的,当然是可能的:

#include <stdlib.h>
struct a
{
int a; 
float b;
};
void *foo()
{
void *v;
((struct a *)malloc(sizeof(struct a))) -> b = 4.0f;
(*((struct a *)malloc(sizeof(struct a)))).b = 6.0f;
*((struct a *)malloc(sizeof(struct a)))  = (struct a){5, 8.0f};
((struct a *)(v = malloc(sizeof(struct a)))) -> b = 4.0f;
return v;
}

https://godbolt.org/z/suW4sp

你的问题的答案取决于你对"可能"的定义。

编写和编译这样的代码肯定是可能的,它将是一个正确的c程序,但它不会有任何意义,因为你从来没有存储过你刚刚写入的数据的实际地址,所以你没有办法在以后的程序中使用它。每次调用malloc函数时,它都会返回新分配的内存区域的新地址,因此每次您尝试像这样访问数据时,它都会是具有不同地址的不同数据。

因此,如果要动态分配struct node并在程序中进一步使用它,则必须像这样编写它:

struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->data = 2;

然后,您可以将该tmp指针用于适合您需求的任何内容。

此外,当您不再需要此数据时,不要忘记使用free取消分配它。