user15112440
user15112440

Reputation:

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

Upvotes: 0

Views: 38

Answers (2)

Furkan
Furkan

Reputation: 361

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

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180518

If q is a pointer to any object type, then casting it to a character type provides a means to access the bytes of the representation of the pointed-to object, if any. However, if q is a pointer to a structure type then the code you present does not access the members per se. Although the representation of an instance of the structure type comprises representations of all the structure members, (char*) q + 1 is not selecting a member, but rather a byte (in the form of a pointer to that byte) -- the one at offset 1 from the beginning of the structure. That byte could be part of the first member (which starts at offset 0), part of the second member, or not part of any member.

Given (char*) q + 1 being a pointer to the byte at offset 1 from the start of object *q, and *q being at least two bytes in size, the expression *( (char*) q + 1) evaluates to the value of that byte. It is equivalent to ((char *)q)[1].

Upvotes: 1

Related Questions