简体   繁体   English

将结构的地址分配给指针

[英]assign struct's address to pointer

Consider this code: 考虑以下代码:

#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;
}

I assign address of p1 in a pointer( p2 ).but when printing the address of p1 and p2 why the address is not same? 我在一个指针( p2 )中分配了p1的地址,但是在打印p1p2的地址时为什么地址不相同?

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

returns 回报

0x7ffc1b96f980 0x7ffc1b96f978 

Can you tell me why? 你能告诉我为什么吗?

In your code, change 在您的代码中,更改

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

to

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

because, &p1 is a pointer to struct , so is p2 (not &p2 ). 因为&p1指向struct指针 ,所以p2 (不是&p2 )也是。

FWIW, &p2 is a pointer to a pointer to struct . FWIW, &p2指向struct的指针 So, 所以,

when printing the address of p1 and p2 why the address is not same? 当打印p1p2的地址时,为什么地址不相同?

because, the the address of p1 is no the same as the address of p2 . 因为p1的地址与p2的地址不同。 The the address of p1 is the value of p2 . p1的地址是p2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM