将结构的地址分配给指针

assign struct's address to pointer

考虑这段代码:

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>

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;
        who.name=strdup(name);
        who.age=age;
        who.height=height;
        who.weight=weight;

        return who;
}
void Person_destroy(struct Person who)
{
        free(who.name);
}
void Person_print(struct Person who)
{
        printf("%s %d %d %d %p \n",who.name,who.age,who.height,who.weight,&who);
}
int main(int argc,char *argv[])
{
        struct Person p1=Person_create("shahrooz",26,180,100);
        Person_print(p1);
        Person_destroy(p1);
        struct Person *p2=&p1;
        printf("%p %p \n",&p1,&p2);
        return 0;
}

我在指针(p2)中分配了p1的地址。但是当打印p1p2的地址时,为什么地址不一样?

printf("%p %p \n",&p1,&p2);

returns

0x7ffc1b96f980 0x7ffc1b96f978 

你能告诉我为什么吗?

在您的代码中,更改

printf("%p %p \n",&p1,&p2);

printf("%p %p\n",&p1,p2);

因为,&p1 是指向结构 的指针,p2 也是(不是&p2)。

FWIW,&p2 是一个 指向结构 的指针。所以,

when printing the address of p1 and p2 why the address is not same?

因为p1的地址和p2的地址不一样。 p1的地址是p2