内存分配的字符数组 [英] Allocation of memory for char array
问题描述
让我们说你有 -
struct Person {
char *name;
int age;
int height;
int weight;
};
如果你这样做 -
struct Person *who = malloc(sizeof(struct Person));
怎么会Ç知道多少内存分配对于名称变量,因为这可以容纳大量的数据/串的?我是新的C和内存分配感到困惑。
How would C know how much memory to allocate for name variable as this can hold a large number of data/string? I am new to C and getting confused with memory allocation.
推荐答案
这不会知道,你将不得不为它单独分配内存。
It won't know, You will have to allocate memory for it separately.
struct Person *who = malloc(sizeof(struct Person));
分配足够的内存来存储类型人
的对象。结果
内部的人
对象名称
只是占据相当于一个指针大小的空间成员焦
。结果
以上的malloc
只分配了太多的空间,才能够做任何有意义的成员指针,你将不得不单独分配内存给它。
Allocates enough memory to store an object of the type Person
.
Inside an Person
object the member name
just occupies a space equivalent to size of an pointer to char
.
The above malloc
just allocates that much space, to be able to do anything meaningful with the member pointer you will have to allocate memory to it separately.
#define MAX_NAME 124
who->name = malloc(sizeof(char) * MAX_NAME);
现在
指向大小的动态内存成员进一步。 124
堆字节,它可以用来名称
Now the member name
points to an dynamic memory of size 124
byte on the heap and it can be used further.
此外,您的使用完成后,你将需要记住免费
它明确或者你会最终有一个内存泄漏。
Also, after your usage is done you will need to remember to free
it explicitly or you will end up with a memory leak.
free(who->name);
free(who);
这篇关于内存分配的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!