Array of Pointers in C
As I told you earlier “Array is a collection of elements of similar data types”. We have already created array of integer, floats and so on. So one question that arises. Can we make array of pointers? Well the answer is yes, of course. To make an array we have to fulfil just one condition i.e it should contain elements of same data type. So we can store pointers of isolated variables inside an array. Lets take one example to understand this.
#include<stdio.h> int main() { int *a[4]; //declaration of array of pointers int x=23,y=54,z=65,p=45,q; a[0]=&x; a[1]=&y; a[2]=&z; a[3]=&p; for(q=0;q<4;q++) printf("%d ",*a[q]); return 0; }
Output
23 54 65 45
Explanation
- In the beginning of the program I have declared a 1D array of pointers with size 4. It means it can store addresses of four isolated pointer variables.
- After that I have declared some integer variables and I have stored some values in it.
- Now I have stored the addresses of integer variables inside array of pointers a.
- In the last I have printed all the values at the addresses stored in that array by using for loop.
Note: We can even store the addresses of other arrays inside array of pointers.
3D Array in C
As the name suggests these are arrays having three dimensions. Generally a programmer rarely use 3D arrays. They are mostly used for some game programming. So I will only give you an overview about that.
Declaration and Initialization of 3D Array
Lets take one example to understand it.
int a[2][2][2]={
{
{13, 56},
{54, 67}
},
{
{64, 87},
{23, 678}
}
};
In C language, 3D arrays treated as a collection of 2D arrays. In the above example we can also say that we are creating two 2D arrays. An example of 3D array is given below which is also a combination of three 2D arrays.
3D Array in C – Image Source |
Memory Allocation of 3D Array
Allocation of memory of 3D array is similar to 2D array. As the elements inside 3D array always stored in contiguous memory locations.