-
Pointers
Hi,
I am having trouble with creating array of pointers and accessing the elements in the array.
For example:
int a1[10][20];
int a2[10][20];
int a3[10][20];
How do I create array of pointers to a1,a2,a3 that is equivalent to a[3][10][20]?
Thanks for your help!
-
Why don't you just create a[3][10][20] ?
Or if you really want to play with pointers...
Code:
int a1[10][20];
int a2[10][20];
int a3[10][20];
int *ptr[3] = {a1,a2,a3};
-
You might also take a look at: Arrays and Pointers
Quzah.
-
reply
CommonTater, thanks for your suggestion. Ii need to create an array of pointers because I have a set of "a" arrays that I need to use depends on the situation.
If you use:
Code:
int *ptr[3] = {a1,a2,a3};
How do I access the content of a1, a2 and a3 via ptr, such as a1[1][1]?
-
Well CommonTater has the right idea, but you need to get the syntax right for "an array of pointers to 2D arrays".
Something like this
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a1[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
int a2[2][3] = { { 10, 20, 30 }, { 40, 50, 60 } };
int (*a3[])[3] = { a1, a2 };
int x, y, z;
for ( x = 0 ; x < 2 ; x++ ) {
for ( y = 0 ; y < 2 ; y++ ) {
for ( z = 0 ; z < 3 ; z++ ) {
printf("%d, ",a3[x][y][z] );
}
printf("\n");
}
}
return 0;
}
$ gcc bar.c
$ ./a.out
1, 2, 3,
4, 5, 6,
10, 20, 30,
40, 50, 60,
-
Salem,
Thanks! That works great! Now, I am running into the next problem. How do i pass a3 into a function and how do I access it in the function?
Thanks in advance for your help.
-
The copy/paste rule works.
Simply copy the declaration of the array you want to pass, and make that the formal parameter.
Code:
#include<stdio.h>
#include<stdlib.h>
void foo ( int (*a3[])[3] ) {
int x, y, z;
for ( x = 0 ; x < 2 ; x++ ) {
for ( y = 0 ; y < 2 ; y++ ) {
for ( z = 0 ; z < 3 ; z++ ) {
printf("%d, ",a3[x][y][z] );
}
printf("\n");
}
}
}
int main()
{
int a1[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
int a2[2][3] = { { 10, 20, 30 }, { 40, 50, 60 } };
int (*a3[])[3] = { a1, a2 };
foo( a3 );
return 0;
}