dynamic memory for 2D char array

One way is to do the following:

char **arr = (char**) calloc(num_elements, sizeof(char*));

for ( i = 0; i < num_elements; i++ )
{
    arr[i] = (char*) calloc(num_elements_sub, sizeof(char));
}

It’s fairly clear what’s happening here – firstly, you are initialising an array of pointers, then for each pointer in this array you are allocating an array of characters.

You could wrap this up in a function. You’ll need to free() them too, after usage, like this:

for ( i = 0; i < num_elements; i++ )
{
    free(arr[i]);
}

free(arr);

I think this the easiest way to do things and matches what you need.

Leave a Comment