C Pointer Confusion

Hello guys, and happy new year!

It’s hard for me to understand pointers in C. As far as I understand, a pointer is a special variable that stores the addresses of regular variables.

I am posting two code samples that are equivalent. In the first I typed in scanf &d1.am.

In the second example, if I change &d1.amto ptd1.am, it throws a compilation 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 that it’s right to dial &(*ptd1).aminstead, but I can’t understand why. How &(*ptd1).amequal &d1.amand ptd1.amno? I clearly typed that ptd1=&d1!

Thanks in advance for your help!

+4
4

. , &. &d1.am &(d1.am), ptd1.am (&d1).am, &d1.am!= (&d1).am.

+7

(.) , - (&). , &d1.am - am d1, int*, ptd1 (struct student *).

+3

, . , &. ptd1.am (& d1).am(., , @haccks).

, ptd1 , , , ->. scanf :

scanf("%d", &(ptd1->am));
+1

As ptd1 = & d1; this means that * ptd1 will point to d1.

So, if you want to access d1.am, you need to write (* ptd1) .am.

But here you go to scanf, and it needs a memory address, so you need to pass it, and therefore you need to put & (* ptd1) .am.

As others (.) Have noted, it has a higher priority, so (.) Will first select its operands, and the expression will be equal to & amp; ((* ptd1) .AM)

Better to use & (ptd1-> am)

0
source

Source: https://habr.com/ru/post/1623805/


All Articles