How can I convert a pointer to a "pointer to array"?
As an example, supose I have a pointer int *data
to some memory block of 15 integers. I would like to do something like:
int (*mat)[5] = data;
so that I can now make:
for(int i = 0; i < 3; i++){
for(int j = 0; j < 5; j++){
mat[i][j] = // Something.
}
}
However, I get a warning with gcc:
warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int (*mat)[5] = data;
and an error with g++:
error: cannot convert ‘int*’ to ‘int (*)[5]’ in initialization
int (*mat)[5] = data;
If I add an explicit cast int (*mat)[5] = (int (*)[5])data;
it compiles without warnings, but i don't know if this yields undefined behavior.
What is the correct way to accomplish this? Can it be made without an explicit cast?
Edit:
I know I can use the int *
pointer like this:
data[5*i + j] = \\ Something.
but in my real situation I need to iterate the array through 3 dimensions,
and the code inside the []
gets very long, thats why I want to use the
mat[i][j]
notation.