C Structure and Pointer

So, we have covered the basics of C structure. Now let’s move on to a little more advanced topic: how C structure can be accessed with pointers.

Look at the code. What are the changes you have found? Let me help

At Line 44, to use pointer, we just wrote player *ptr = &player1; to store address of player1 in ptr pointer. Is it hard to get? I guess no, as this is the common way to use pointer.

Basic 1: When you are dealing with struct pointers, to access struct members, just use -> instead of dot (.) we used earlier while dealing with struct variables. 

That’s why we wrote ptr->name and ptr->age in line 45, 46, and 47 to access the member variables.

Basic 2: (*ptr) is equivalent to player1 

(*ptr) is nothing but player1 (Just same as the pointer story). When dealing with (*ptr), do not forget to access the members with dot(.) operator. That’s what I did at line 50.

So in final words, look at the following:

ptr->name //valid

ptr->age // valid

ptr.name // not valid, as ptr is a struct pointer

ptr.age  //not valid, as ptr is a struct pointer

player1.name //valid

player1.age //valid

(*ptr)->name // not valid, as (*ptr) is a struct variable

(*ptr)->age //not valid, as (*ptr) is a struct variable

(*ptr).name // valid

(*ptr).age //valid

Finally, take a look at the output

I hope you have got it. Thanks!