[英]pointers to structs versus malloc in C?
#include<stdio.h>
typedef struct telephone
{
char *name;
int number;
} TELEPHONE;
int main()
{
//TELEPHONE index;
TELEPHONE *ptr_myindex;
ptr_myindex = (TELEPHONE*)malloc(sizeof(TELEPHONE));
//ptr_myindex = &index;
ptr_myindex->name = "Jane Doe";
ptr_myindex->number = 12345;
printf("Name: %s\n", ptr_myindex->name);
printf("Telephone number: %d\n", ptr_myindex->number);
free(ptr_myindex);
return 0;
}
When I compile this, it outputs the same result as when I don't dynamically allocate the pointer to the struct, and instead use the part in my code that has been commented out. 当我对此进行编译时,它输出的结果与不动态分配该结构的指针时的结果相同,而是使用我的代码中已注释掉的部分。 Why does this happen? 为什么会这样?
When you declare: 当您声明:
TELEPHONE index
The compiler knows what kind of struct TELEPHONE
is and so it allocates the memory needed by that struct. 编译器知道TELEPHONE
是哪种结构,因此它将分配该结构所需的内存。
For example: 例如:
int a = 5;
int *p = &a;
It's perfect. 这是完美的。 But if we want to achieve the same without int a = 5
, we should do the following: 但是,如果要在没有int a = 5
情况下达到相同的效果,则应执行以下操作:
int *p;
p = (int*)malloc(sizeof(int));
*p = 5;
There's a difference tough. 有一个艰难的区别。 The first code allocate the variable in the stack
, while the second code allocate it in the heap
. 第一个代码在stack
分配变量,而第二个代码在heap
分配变量。 But in the second case, there's no allocated space for the struct before the malloc
, and the only allocated space is for the pointer itself (that do not need the same space as the struct itself). 但是在第二种情况下,在malloc
之前没有为该结构分配空间,并且唯一的分配空间是指针本身(不需要与结构本身相同的空间)。
Your two versions of code do the following: 您的两个版本的代码执行以下操作:
These options are interchangeable in this program. 这些选项在该程序中可以互换。 The code that assigns to the struct, and then prints, doesn't care whether the struct was heap allocated or is a local variable. 分配给该结构然后打印的代码不在乎该结构是堆分配的还是局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.