Hello guys and a happy new year!
I have difficulty understanding pointers in C language. As far as I learned a pointer is a special variable that stores addresses of regular variables.
Ι am posting two samples of code which are equivalent. In the first I typed into scanf the &d1.am.
In the second sample if I change the &d1.am to ptd1.am it pops up a compile error and I cannot understand why.
struct student{
int am;
char stname[20];
char stsurname[20];
};
int main(){
struct student d1;
printf("1st student\n");
printf("Enter am\n");
scanf("%d", &d1.am)
Second equivalent sample:
struct student{
int am;
char stname[20];
char stsurname[20];
};
int main(){
struct student d1;
struct student *ptd1;
ptd1=&d1;
printf("1st student\n");
printf("Enter am\n");
scanf("%d", &(*ptd1).am);
I know the correct is to type &(*ptd1).am instead but I can't figure why. How &(*ptd1).am is equal to &d1.am and ptd1.am is not? I typed clearly that ptd1=&d1!
Thanks in advance for your help!
. operator has higher precedence than unary &. &d1.am is equivalent to &(d1.am) while ptd1.am is equivalent to (&d1).am, that said &d1.am != (&d1).am.
The structure access operator (.) has higher precedence than the address-of operator (&). So &d1.am is the address of the am member of d1, which is an int*, which differs from the type of ptd1 (struct student *).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With