Is it possible to create an array of arrays in c
Thank you.
Is it possible to create an array of arrays in c
Thank you.
It's the same as for example in PHP:
int arrayInArray[10][50];
You read data out of it with:
printf("%d", arrayInArray[3][37]);
I bet you mean Multi Dimensional Array instead of "array of arrays".
Some links for this topic:
For using an array of arrays with all the power of C you should have some knowledge of dynamic memory handling in c, with the functions malloc, realloc, and free, and some knowledge about pointers. For this example that you ask a possible solution would be this:
#include <stdio.h>
void main(int argc, char* argv[]){
int** myArray; /* This would be a double pointer, because you want a two dimension array.*/
int firstDimension = 10;
int secondDimension = 20;
int i;
myArray = (int**)malloc(firstDimension*sizeof(int*)); This way you initialize the first dimension of the array.
for(i = 0; i < firstDimension; i++){
myArray[i] = (int*)malloc(secondDimension*sizeof(int));
}
/*Once you have the array initialized, you can access in the way myArray[i][j];*/
/*For releasing resources */
for(i = 0; i < firstDimension; i++){
free(myArray[i]);
}
free(myArray);
}
This is the dynamic way, the one that is teached on CS courses.
If you need an array of arrays then you should use structs.
typedef ArrayStruct* ArrayStructPtr;
struct ArrayStruct
{
void* array;//Node array
ArrayStructPtr arrays;//Pointer to sub arrays
};
int main()
{
ArrayStruct* a;//Declare Some Arrays
a=(ArrayStruct*)malloc(sizeof(ArrayStruct)*N);
for(int i=0;i<N;i++)
{
a[i].array=(void*)malloc(sizeof(int)*N);//Malloc the actual array
a[i].arrays=NULL;//Malloc subarrays if needed
}
//add subarray on array 0
ArrayStruck * temp=(ArrayStruct*)malloc(sizeof(ArrayStruct));
temp->array=(void*)malloc(sizeof(char)*MAXNAME*N);
temp->arrays=NULL;
a[0]=arrays=temp;
return 0;
}
What you need is a List Of arrays Where each node of the struct can hold an array and a pointer to another node. The array type is void* to support int,float,char*.
So each array can have as many subarrays as you want.You can create 3 dimension Arrays if you want!