0

I have read throught a lot of articles explaining the concept of pointers, but i am not able to find out, why my code gives me an "incompatible pointer type" warning. Hopefully you guys can help me.

int cube[3][2][4] = {{{1,2,3,4}},{{2,3},{4,6,8,10}},{{3,4,5,6},{6,8,10}}};
int x = 1;
int y = 1;
int z = 1;
int *p = &cube[0][0][0];
int (*vptr)[2][4] = cube[x][y]; //This line throws a warning, when i compile it.
int (*mptr)[4] = cube[x];

Then i would like to access cube[x][y][z] with my pointers p, vptr, mptr. I have tried this, but it doesn't work.

printf("%d",*(*(*(p+x)+y)+z));
printf("%d",*(vptr+z));
printf("%d",*(*(mptr+y)+z));

I have read online, that you can access an array element like this:

*(*(array + row) + col)

But my code doesn't work. The first printf throws an error "invalid type argument of unary" and the second printf doesn't work, but the third works. I don't understand this. I would really appreciate it, when someone could explain this behaviour to me or can link me an explanations.

Thank you for your time and your help. Greetings Mike.

Mike
  • 37
  • 1
  • 1
  • 4

2 Answers2

1

What you have probably meant is:

#include <stdio.h>

int main(void)
{
    int cube[3][2][4] = {{{1,2,3,4}},{{2,3},{4,6,8,10}},{{3,4,5,6},{6,8,10}}};
    int x = 1;
    int y = 1;
    int z = 1;

    int *p = &cube[0][0][0];
    int (*vptr)[2][4] = cube;
    int (*mptr)[4] = cube[x];

    printf("%d\n", *p);
    printf("%d\n", *(*(*(vptr+x)+y)+z));
    printf("%d\n", *(*(mptr+y)+z));

    return 0;
}

This line:

int (*vptr)[2][4] = cube[x][y];

does not do what you want. The value of cube[x][y] has type int *, which does not match to declared type of vptr (pointer to two-elements array of four-elements arrays of type int).

In order to print int value with %d format specifier and vptr you can access it by either:

vptr[x][y][z],

or

*(*(*(vptr+x)+y)+z)).

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
0

The problem with the first printf is that cube is not an array of pointers to an array of pointers to an array of int. In memory it is an array of integers. When you cast it to the int* the compiler interprets it as a array of int, a 1D array to be precise. Thats why *(*(array + row) + col) doesn't works.

The first printf statement should be

printf("%d", *(p + x*2*4 + y*4 + z));
Vincent
  • 648
  • 3
  • 9