是否可以像这样编写c malloc函数代码
Is it possible to write c malloc function code like this
在堆上分配内存时感到困惑?
如果我这样写初始化堆内存中的变量
((struct node*)malloc(sizeof(struct node)).data=2
我可以这样写而不是使用指针吗?
如果我声明节点类型变量,那么可以这样写还是不这样写?
如果我不通过访问直接地址使用指针。
您问题的答案取决于您对 "possible" 的定义。
编写和编译这样的代码绝对是可能的,它是一个正确的 c 程序,但它没有任何意义,因为您从未存储过您刚刚编写的数据的实际地址,所以您以后无法在程序中访问它。每次你调用 malloc
函数时,它都会 returns 新分配的内存区域的新地址,所以每次你试图访问你的数据时,它都会是具有不同地址的不同数据.
所以,如果你想动态分配一个 struct node
并在你的程序中进一步使用它,你必须这样写:
struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->data = 2;
然后您可以根据需要使用该 tmp
指针。
此外,当您不再需要此数据时,不要忘记使用 free
取消分配它。
是的,当然有可能:
#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;
}
在堆上分配内存时感到困惑?
如果我这样写初始化堆内存中的变量
((struct node*)malloc(sizeof(struct node)).data=2
我可以这样写而不是使用指针吗? 如果我声明节点类型变量,那么可以这样写还是不这样写? 如果我不通过访问直接地址使用指针。
您问题的答案取决于您对 "possible" 的定义。
编写和编译这样的代码绝对是可能的,它是一个正确的 c 程序,但它没有任何意义,因为您从未存储过您刚刚编写的数据的实际地址,所以您以后无法在程序中访问它。每次你调用 malloc
函数时,它都会 returns 新分配的内存区域的新地址,所以每次你试图访问你的数据时,它都会是具有不同地址的不同数据.
所以,如果你想动态分配一个 struct node
并在你的程序中进一步使用它,你必须这样写:
struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->data = 2;
然后您可以根据需要使用该 tmp
指针。
此外,当您不再需要此数据时,不要忘记使用 free
取消分配它。
是的,当然有可能:
#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;
}