Given is this function
void printMatrix(int *m, int ze, int sp)
Now *m is supposed to be a 2 dimensional array (or more like a pointer to a 2 dimensional array).
So how can I use this *m as m[][] ?
Given is this function
void printMatrix(int *m, int ze, int sp)
Now *m is supposed to be a 2 dimensional array (or more like a pointer to a 2 dimensional array).
So how can I use this *m as m[][] ?
Variable-Length Arrays can help you here:
int (*p)[sp] = (void*) m;
Now you can access the elements via p[i][j].
About the well-definedness of the cast with respect to strict aliasing rules: it is valid, because both m and p point to compatible types.
p is a pointer to array of integers (though the syntax might be confusing), which is surely compatible with a pointer to array of integers :) Update No..wait. Something is not right here.. let me digest it...p[i] point to. Apparently it would point to the ith "row" *(p + sp*sizeof(int))int(*)[n] and int* are not compatible types, that's not why this is ok. But I believe a pointer-to-type can always be coverted to an array-pointer-to-type without violating strict aliasing. "An object shall have its stored value accessed only by an lvalue expression that has one of the following types:" /--/ "an aggregate or union type that includes one of the aforementioned types among its members". An int array is an aggregate and it includes int among its members.You cannot, as m can be dereferenced only once. But if you know the dimensions of the array, you can calculate the 1D index as
element[i][j]=m[i * width + j];
element[i][j]=m[i * width + j];= means "is expressed as" here, not an actual copy to a new array.You will have to assume that it is a so-called "mangled" array. In which case you can create a new array as a VLA:
void printMatrix(int *m, int ze, int sp)
{
int array[ze][sp];
memcpy(array, m, sizeof(int[ze][sp]));
}
Or perhaps as a dynamically allocated 2D array:
void printMatrix(int *m, int ze, int sp)
{
size_t size = sizeof(int[ze][sp]);
int (*array)[sp] = malloc(size);
memcpy(array, m, size);
...
}
Converting the int* to an array pointer type is however questionable practice, which will cause pointer aliasing problems. The best is of course if you can rewrite the function prototype to properly use a 2D array instead.
int* array = malloc(x*y*sizeof(int))