Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Accessing (int) via (void *) pointing to (void *) pointing to (int) by typecasting and dereferencing

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 = &num;        // 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:

scheme

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?

like image 646
finefoot Avatar asked May 20 '16 23:05

finefoot


1 Answers

Are there alternatives to access the integer?

 int num = 42;
 int *vptrB = &num;
 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.

like image 169
chux - Reinstate Monica Avatar answered Oct 28 '22 15:10

chux - Reinstate Monica