【发布时间】:2015-11-09 01:46:40
【问题描述】:
我试图了解 C 中 struct 的内存分配,但我被困住了。
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的大小是如何计算的,因为名称仅指向 第一个字符?
【问题讨论】:
-
4的间隙是char*的大小。最后一个空白是 char* 而不是指针的地址
-
要打印带有
printf的指针,请使用"%p"格式代码。 -
@joachimpileborg 并使用
%zu代替size_t。 -
%d对应的参数类型必须为int;您提供了一个size_t值,它调用了未定义的行为。也许你的意思是%zu。类似地,对应于%x的参数类型应该是unsigned int,但是您已经提供了各种指针值......也许您打算使用%p并强制转换为(void *)。assert应该用作调试辅助,而不是错误处理功能。这些用词不当使我对您正在阅读的书感到担忧;顺便问一下,那本书是什么? -
顺便说一下,没有要求两个连续的内存分配应该返回两个连续的内存块。你也不要打印
name成员的位置,而是@返回的指针987654339@ 调用(它本身调用malloc),要打印name成员的位置,您应该使用地址运算符&,就像其他人一样。这也是造成 4 到 5 之间“差距”的原因之一。
标签: c memory memory-management struct malloc