Search code examples
cpointersoutputcharacterstructure

How to access the members of structure through pointers same as we access array?


I got a Question in a mock test which is not running in IDE but I could not understand the concept behind that piece of code given in test.

printf (“%c, %c”, *( (char*) q + 1) , *( (char*) q + 2) ) ; Here how an pointer to struct q can access the members of pointers using numbers.

Here is the link for the code

https://ide.geeksforgeeks.org/7V6mVJZvre


Solution

  • In c, struct members just memory space mapped to that struct definition. A struct with three chars means 3 byte space mapped to the this struct.

    q is a pointer. So q + 1 means one address forward to the base struct address

    (char*) means this is not a struct anymore this is a char pointer

    *( (char*) q + 2) ) or simply *x means dereference the pointer so get the char value.

    There are some exceptions (if not all members are the same type) check Structure padding and packing