我试图理解 C 语言中结构的内存分配,但我一直坚持下去。
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->age = age;
who->height = height;
who->weight = weight;
who->name = strdup(name);
return who;
}
int main(int argc, char *argv[])
{
struct Person *joe = Person_create("ABC", 10, 170, 60);
printf("Size of joe: %d\n", sizeof(*joe));
printf("1. Address of joe \t= %x\n", joe);
printf("2. Address of Age \t= %x\n", &joe->age);
printf("3. Address of Height \t= %x\n", &joe->height);
printf("4. Address of Weight \t= %x\n", &joe->weight);
printf("5. Address of name \t= %x\n", joe->name);
...
我不明白的是这个结构的内存分配。在我的打印输出中,我看到了这个:
Size of joe: 24
1. Address of joe = 602010
2. Address of Age = 602018
3. Address of Height = 60201c
4. Address of Weight = 602020
5. Address of name = 602030
问题:
- 为什么 1 和 2 之间有差距?
- 为什么 4 和 5 之间有间隙?
*name
的大小是如何计算的,因为 name 仅指向 第一个字符?
最佳答案
对象地址joe
之间没有空隙和数据成员的地址 age
.此范围被数据成员占用 name
.
struct Person {
char *name;
int age;
//...
根据输出
1. Address of joe = 602010
2. Address of Age = 602018
占用8个字节即sizeof( char * )
在你的平台中等于8。它的地址与对象的地址joe
一致。本身。
在这个声明中
printf("5. Address of name \t= %x\n", joe->name);
你没有输出name
的地址本身。您打印了存储在该指针中的值,该值是字符串文字副本的第一个字符的地址 "ABC"
这是通过使用 strdup
获得的.
所以输出 4 和 5 中的值之间存在差距,因为它们是不同的内存范围。资料员weight
属于对象joe
而字符串文字的副本 "ABC"
存储在对象之外。该对象只有数据成员 name
指向文字副本的第一个字符。
作为name
是一个指针那么它的大小计算如下
sizeof( char * )
或
sizeof( joe->name )
正如我在文章开头所解释的,等于 8。
如果你想确定字符串文字的长度,你应该使用标准函数 strlen
在 header 中声明 <string.h>
.例如
printf( "%zu\n", strlen( joe->name ) );
关于使用 malloc 为结构体分配 C 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32033175/