带有malloc的struct的C内存分配

前端之家收集整理的这篇文章主要介绍了带有malloc的struct的C内存分配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图理解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之间存在差距?
> *名称的大小如何计算为名称仅指向
第一个炭?

解决方法

对象joe的地址与数据成员年龄的地址之间没有间隙.此范围由数据成员名称占用.
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);

你没有输出名称本身的地址.您打印了存储在此指针中的值,此值是使用strdup获取的字符串文字“ABC”的副本的第一个字符的地址.

因此,输出4和5中的值之间存在差距,因为它们是不同的存储器范围.数据成员权重属于对象joe,而字符串文字“ABC”的副本存储在对象外部.该对象只有数据成员名称,指向文字副本的第一个字符.

由于name是指针,因此其大小计算如下

sizeof( char * )

要么

sizeof( joe->name )

如我在帖子开头所解释的那样等于8.

如果要确定字符串文字的长度,则应使用标题< string.h>中声明的标准函数strlen.例如

printf( "%zu\n",strlen( joe->name ) );
原文链接:https://www.f2er.com/c/117074.html

猜你在找的C&C++相关文章