Reputation: 37
I would like to declare a pointer to a 3d array in a manner that I could index it with one dimension less than original array, example: ptr[i][j]. I'm using some structure in which I would like this pointer to be stored so I could access it later.
I've done this with the 2d arrays but I declared a pointer to an array of pointers to 2d arrays:
typedef const unsigned char* ptrType;
const ptrType ptrArray[] = {...};
And this is what I'm trying for the 3d array:
typedef const unsigned char** ptrType;
typedef struct structP
{
ptrType arrayPtr;
};
and in the main I'm doing something like this:
struct structP test;
test.arrayPtr = *myThreeDArray;
when trying to access elements via pointer this is the only thing that compiler let me do:
&(test.arrayPtr[i][j]);
Also myThreeDArray is defined like this:
const unsigned char myThreeDArray[2][23][25] = { ... };
Doing it in a way that is described gives me unspected results at the output. Some garbage values.
Any ideas how to do this in a proper way?
Upvotes: 0
Views: 8291
Reputation: 44246
What you seem to want is a pointer to a 2D array
For integers this could be like:
#include <stdio.h>
void print_3d(int (*p3d)[3][4])
{
for (int i=0; i<2; ++i)
for (int j=0; j<3; ++j)
for (int k=0; k<4; ++k)
printf("%d ", p3d[i][j][k]);
}
int main(int argc, char *argv[])
{
int arr3d[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}}
};
int (*p_to_arr3d)[3][4] = arr3d; // Get a pointer to int[3][4]
print_3d(p_to_arr3d); // Use the pointer
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
In case you are dealing with strings, it could be like:
#include <stdio.h>
void print_3d(char (*p3d)[3][20])
{
for (int i=0; i<2; ++i)
for (int j=0; j<3; ++j)
printf("%s ", p3d[i][j]);
}
int main(int argc, char *argv[])
{
char arr3d[2][3][20] = {
{"this", "is", "just"},
{"a", "little", "test"}
};
char (*p_to_arr3d)[3][20] = arr3d; // Get a pointer to char[3][20]
print_3d(p_to_arr3d);
}
Output:
this is just a little test
Using the same syntax as above you can store the pointer in a struct:
struct myData
{
char (*p_to_char_arr)[3][20];
int (*p_to_int_arr)[3][4];
};
Upvotes: 2