dynamic memory for 2D char array

后端 未结 6 591
别那么骄傲
别那么骄傲 2020-12-01 07:03

I have declared an array char **arr; How to initialize the memory for the 2D char array.

6条回答
  •  無奈伤痛
    2020-12-01 07:41

    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.

提交回复
热议问题