I have a function which returns a 3-d array of integers as a pointer to the 0th 1-D array of the 0th 2-D array in it. It is of dimensions 2*3*4
. Here is my function:
int (*ultimate())[4] {
int a[2][3][4] = {
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
},
{
{13,14,15,16},
{17,18,19,20},
{21,22,23,24}
}
};
return (int (*)[4]) a;
}
I am using this function in two different ways:
In the first method, I am taking the pointer to the 1-D array, and seeing that there are 6 such arrays, print out each one by one:
int (*q)[4];
q = ultimate();
for (int i = 0; i < 2*3; i++) {
printf("\n");
for (int k = 0; k < 4; k++) {
printf("%d ",*(*(q+i)+k));
}
}
In the next method, I am simply using the return value to get the address of the first element in the 3-D array, and then printing all:
int *p;
for (int i = 0; i < 2; i++) {
p = (int *) (q+i*3);
pnl();
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
printf("%d",*p);
p++;
}
}
}
However, in both cases, I am getting junk values. In the first method, I am getting some rows of the array while the other values are junk, while in the second method all values are junk. Any idea where I am being wrong?