dynamic memory for 2D char array

后端 未结 6 622
别那么骄傲
别那么骄傲 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:44

    There are two options for allocating an array of type char **

    I've transcribed these 2 code samples from the comp.lang.c FAQ (which also contains a nice illustration of these two array types)

    Option 1 - Do one allocation per row plus one for the row pointers.

    char **array1 = malloc(nrows * sizeof(char *)); // Allocate row pointers
    for(i = 0; i < nrows; i++)
      array1[i] = malloc(ncolumns * sizeof(char));  // Allocate each row separately
    

    Option 2 - Allocate all the elements together and allocate the row pointers:

    char **array2 = malloc(nrows * sizeof(char *));      // Allocate the row pointers
    array2[0] = malloc(nrows * ncolumns * sizeof(char)); // Allocate all the elements
    for(i = 1; i < nrows; i++)
      array2[i] = array2[0] + i * ncolumns;
    

    You can also allocate only one memory block and use some arithmetic to get at element [i,j]. But then you'd use a char* not a char** and the code gets complicated. e.g. arr[3*ncolumns + 2] instead of arr[3][2]

提交回复
热议问题