I'm fiddling around with pointers in C and am still uncertain about some very basics. I came up with the following exemplary code:
#include <stdio.h>
int main(void)
{
int num = 42; // we want to access this integer
void *vptrB = # // pointer B points to the integer
void *vptrA = &vptrB; // pointer A points to pointer B
printf("%d\n", * (int *) * (void **) vptrA);
return 0;
}
The memory should look something like this:
Are there alternatives to access the integer? Anything bad/unsafe with the example? Is * (int *) * (void **) vptrA
the only way to access num
via vptrA
and vptrB
?
Are there alternatives to access the integer?
int num = 42;
int *vptrB = #
int **vptrA = &vptrB;
// All print 42
printf("%d\n", num);
printf("%d\n", *vptrB);
printf("%d\n", **vptrA);
Anything bad/unsafe with the example?
Use of void*
to represent the address to data loses type, alignment, const
and volatile
information. void*
obliges the use of casting to subsequently interpret the referenced data - this is prone to error. Although the code is correct in its casting, it is subject to maintenance mistakes and code review mis-understandings.
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