Lets say I have a structure :
struct ABC
{
char a;
char b;
char c;
}
I can declare a pointer to a pointer to the above structure as :
struct ABC** abc
Now abc
is a pointer pointing to the structure pointer *abc
and *abc
is a structure pointer pointing to the structure abc
. Thus; sizeof(**abc)
will be 4, sizeof(*abc)
will also be 4 and sizeof(abc)
will be 3 (considering pointers are 4 bytes in size and characters are 1 byte in size).
My question is this:
How to declare a character pointer that points to the member variable c
using abc
that was declared above ?
To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.
In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.
As we know Pointer is a variable that stores the address of another variable of data types like int or float. Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures.
To use pointers in C, we must understand below two operators. To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
sizeof(**abc) will be 4, sizeof(*abc) will also be 4 and sizeof(abc) will be 3
I think that should be, assuming no padding of the structure,
sizeof(**abc) will be 3, sizeof(*abc) will also be 4 and sizeof(abc) will be 4
^^^ ^^^
Change here change here
To get a pointer to member variable c do
&(*abc)->c
Note the paranthesis around *abc
. The reason for this is that ->
has a higher precedence than *
and so you need to make sure the first dereference (to go from pointer-to-pointer to pointer) happens first.
Or you can do
&(**abc).c
Same reason for the parenthesis... need to make sure you've dereferenced (twice) before applying the member-selection-via-object-name .
.
Provided all of your pointers are valid, so that you can dereference them, you can do it like this:
char* a_ptr = &((*abc)->a);
or
char* b_ptr = &((**abc).b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With