简体   繁体   中英

Pointer to a structure

The pointers when declared to atomic data types such as int work like this

int a,*b=&a;

printf("\n The address of pointer b = %p",&b); //Here using & operator we get the memory location where the pointer b is stored itself

printf("\n The pointer b points to %p this memory location",b); //The will give me the value of ptr and that value is the memory address of the variable a

printf("\n The value at the memory where pointer b points is %d",*b);//Using * operator we get the value stored at the memory location hold by b

But there is some confusion when we use pointer to structure

#include<stdio.h>
struct A{
    int age;
    int roll_no;
    float marks;
};
int main(void)
{
    struct A obj1;
    struct A *ptr;
    printf("\n The addrees of the obj1 is =%p",&obj1);
    printf("\n The address of the variable age is %p ",&obj1.age);

    ptr=&obj1;
    printf("\n THe pointer ptr points to %p ",ptr); //This will give me the memory location where pointer ptr is pointing to.

    printf("\n The memory address of pointer ptr itself is %p ",&ptr); //This will give the memory location where the pointer ptr is itself store. So far So good

    printf("\n The memory location of variable age is %p",&ptr->age); //Why I have to use this & operator to find the address of the age and we also do not use * opertaor here I guess 

/* Should not ptr->age give me the memory address and *ptr->age give me the value ? */


    return 0;
} 

I am confused with the usage of operator here

语法ptr->age(*ptr).age的缩写。

Keep in mind that ptr->age is the same as (*ptr).age . This means that you get the value of age when you use ptr->age . So you need & to get its address.

*ptr->age is the same as *(ptr->age) which is the same as *((*ptr).age) which is invalid syntax and the compiler will issue a diagnostic. You are trying to dereference a value here as ptr->age gives the value of age and it cannot be dereferenced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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