Two dimensional char array

C programming

For some application we need to make two dimensional array which means we need an array of arrays. An example of such application is array of strings, because, as we know, string is defined as array of characters.

The best for us is write function called alloc_array which will do all the work for us.

function:

char ***alloc_array(int x, int y) {
    char ***a = calloc(x, sizeof(char **));
	int i;
    for(i = 0; i != x; i++) {
        a[i] = calloc(y, sizeof(char *));
    }
    return a;
}

Now we can use function in concrete project.

#include <stdio.h>
#include <stdlib.h>

char ***alloc_array(int x, int y) {
char ***a = calloc(x, sizeof(char **));
int i;
for(i = 0; i != x; i++) {
a[i] = calloc(y, sizeof(char *));
}
return a;
}

int main() {
int lin = 5;
int col = 6;
int i, j;

char ***a = alloc_array(lin, col);

//fill some strings for each part of array
for(i = 0; i &lt; lin; i++) {
for(j = 0; j &lt; col; j++) {
a[i][j]=" char ";
}
}
a[2][1] = " foo ";

//write content of array
for(i = 0; i &lt; lin; i++) {
for(j = 0; j &lt; col; j++) {
//printf a[i][j];
printf("%s", a[i][j]);
}
printf("\n");
}
}

Now we can test what it will do.

# ./test
 char  char  char  char  char  char
 char  char  char  char  char  char
 char  foo   char  char  char  char
 char  char  char  char  char  char
 char  char  char  char  char  char
#

The result is exactly what we expected.

Leave a Reply