Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer confusion in C programming language

Tags:

c

pointers

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!

like image 271
Mr T Avatar asked Dec 19 '22 20:12

Mr T


2 Answers

. 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.

like image 192
haccks Avatar answered Jan 13 '23 22:01

haccks


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 *).

like image 33
Michael Avatar answered Jan 13 '23 20:01

Michael