Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Malloc Multidimensional Char Array

I would like to dynamically allocate (malloc) a multidimensional character array in C. The array would have the following format:

char *array[3][2] = {
    {"one","two"},
    {"three","four"},
    {"five","six"}
};

Before the array would be created, I would already know the number of rows and the lengths of all of the characters arrays in the multidimensional array. How would I malloc such a character array?

Thanks in advance!

like image 384
Sheldon Juncker Avatar asked Dec 21 '22 00:12

Sheldon Juncker


1 Answers

This is one way to allocate a two dimensional array of char *.

Afterwards, you can assign the contents like a[1][2] = "foo"; Note that the elements of the array are initialized to (char *)0.

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

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

int main() {
    char ***a = alloc_array(3, 2);
    a[2][1] = "foo";
    printf("%s\n", a[2][1]);
}

[Charlies-MacBook-Pro:~] crb% cc xx.c
[Charlies-MacBook-Pro:~] crb% a.out
foo
like image 91
Charlie Burns Avatar answered Jan 03 '23 03:01

Charlie Burns