Search code examples
cpointersmultidimensional-arraypointer-arithmetic

Printing a pointer of an 3D array element using pointer arithmetics


I am testing how to use array name with pointer arithmetic to access an array elemnets and I have come up with this program:

#include <stdio.h>

int main(){

    // definition of array using designators
    int a[2][2][2] = {
        [0] = {[0] = {1, 2}, [1] = {3, 4}},
        [1] = {[0] = {5, 6}, [1] = {7, 8}}
    };

    printf("7th  element (pointer):  %p\n", *(*(a + 1) + 1) + 0);
    printf("8th  element (pointer):  %p\n", *(*(a + 1) + 1) + 1);

    return 0;
}

Although program works and prints everything correct:

7th  element (pointer):  0x7ffd4b09a1c8
8th  element (pointer):  0x7ffd4b09a1d0

I get warnings at compile time saying something like this for every line where I use %p place holder inside printf():

warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Wformat=]
  printf("7th  element (pointer):  %p\n", *(*(a + 1) + 1) + 0);
                                   ~^     ~~~~~~~~~~~~~~~~~~~
                                   %ls

So at the first glance it looks like I have to simply cast the pointers to (void *) and if I do this and change line:

printf("8th  element (pointer):  %p\n", *(*(a + 1) + 1) + 1);

With this line:

printf("8th  element (pointer):  %p\n", (void *)(*(a + 1) + 1) + 1);

I get a warning:

warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]
  printf("8th  element (pointer):  %p\n", (void *)(*(a + 1) + 1) + 1);
                                                             ^

and compiler calculates a different address for 8'th element and this address is only 1 byte larger than preceeding elemnet's address:

7th  element (pointer):  0x7ffd9e5e1bf8
8th  element (pointer):  0x7ffd9e5e1bf9

I also tried to fix it like this (added one more braces):

printf("8th  element (pointer):  %p\n", (void *)((*(a + 1) + 1) + 1));

and warning was gone, but address is still calculated differently:

7th  element (pointer):  0x7ffca6c6c468
8th  element (pointer):  0x7ffca6c6c470

It looks like compiler needs pointer type to calculate the addresses and if I cast it it will not calculate the address corectly. Does anyone have any idea what I can do to remove the warning and get address calculated in a right way?


Solution

  • If you need the arithmetic to be on int*, and the value to be look at as void*, cast the value after you're doing the arithmetics:

    printf("7th  element (pointer):  %p\n", (void *)((int*)*(*(a + 1) + 1) + 0));
    printf("8th  element (pointer):  %p\n", (void *)((int*)*(*(a + 1) + 1) + 1));