How do you declare an array of arrays of arrays? Say I have an array s[]. s[0] will contain an other array a[] and a[0] will contain an array b[]. How would you do it with pointers?
2 Answers
// b is an array of int. (N is some number.)
int b[N];
// a Option 0: a is an array of M arrays of N int. (M is some number.)
int a[M][N];
// a Option 1: a is an array of M pointers to int.
int *a[M];
a[0] = b;
// Other elements of a must also be assigned in some way.
// s Option 0: s is an array of L arrays of M arrays of N int. (L is some number.)
int s[L][M][N];
// s Option 1: s is an array of L arrays of M pointers to int.
int *s[L][M];
s[0][0] = b;
// Other elements of s must also be assigned in some way.
// s Option 2: s is an array of L pointers to arrays of N int.
int (*s[L])[N];
s[0] = a; // Can use a from a Option 0, not a from a Option 1.
// Other elements of s must also be assigned in some way.
// s Option 3: s is an array of L pointers to pointers to int.
int **s[L];
s[0] = a; // Can use a from a Option 1, not a from a Option 0.
// Other elements of s must also be assigned in some way.
There are also options in which each object is a pointer at its highest level, instead of an array. I have not shown those. They would require defining something for the pointer to point to.
3 Comments
wallyk
+1: Nice answer especially for answering questions the OP should have asked but didn't know enough to do so.
anatolyg
Don't you want to do
s[0] = a in option 2? (to make it 3-dimensional)Eric Postpischil
@anatolyg: Yes, I think that is better.
A simple approach.
int length = 10;
int b[5] = {0,1,2,5,4};
int c[7] = {1,2,3,4,5,6,7};
int** s = malloc(sizeof(int*) * length);
s[1] = b;
s[2] = c;
and so on...
This example is for 2 layer. Making pointer s to be ***s and appropriate changes, to make it 3 layer.
3 Comments
Eric Postpischil
s+1 and s+2 are not lvalues and cannot be on the left side of assignments. You may have intended s[1] and s[2]. And this gives s only two layers, not the three requested in the question.Muthu Ganapathy Nathan
@EricPostpischil ya you are correct.
s+1 is not compiling. But I thought s+1 to be a syntatic sugar of s[1]. Ref : For instance, in the C language the a[i] notation is syntactic sugar for *(a + i) - Wikipedia.dreamlax
@EAGER_STUDENT:
s+1 is not *(s+1). The asterisk makes a world of difference.
s[0]to be an array or to be a pointer to the elements of an array? Do you wanta[0]to be an array or to be a pointer to the elements of an array?