Can somebody please tell me how do I use three dimenssional arrays. eg char ***array
Printable View
Can somebody please tell me how do I use three dimenssional arrays. eg char ***array
A simple example using a dynamic 3D array:
Code:#include <stdio.h>
const int a = 10;
const int b = 4;
const int c = 100;
int main(void)
{
int i, j;
char ***array;
/* allocate memory */
array = (char ***) malloc(a * sizeof(*array));
for(i = 0; i < a; i++)
{
array[i] = (char **)malloc(b * sizeof(**array));
for(j = 0; j < b; j++)
array[i][j] = (char *)malloc(c * sizeof(***array));
}
/* fill array */
for(i = 0; i < a; i++)
for(j = 0; j < b; j++)
sprintf(array[i][j], "%d - %d", i, j);
/* print array */
for(i = 0; i < a; i++)
for(j = 0; j < b; j++)
printf("%s\n", array[i][j]);
/* free memory */
for(i = 0; i < a; i++)
{
for(j = 0; j < b; j++)
free((void *)array[i][j]);
free((void *)array[i]);
}
free((void *)array);
return 0;
}
If you are asking because you say code that has a char ***array in it then I should point out that this is probably not a three dimensional array. You'll usually see this when one needs a pointer to a 2d array or a pointer to a pointer to an array. Using a char *** as a parameter in a function which allocates memory for a char ** is not uncommon.
Code:
void ArrayAlloc(char ***array, int width, int height) {
int w;
*array = (char **array)malloc(height*sizeof(char *));
for(;--height;)
(*array)[height] = (char *)malloc(width);
}
int main(void) {
char **array;
ArrayAlloc(&array, 20, 20);
return 0;
}