Search code examples
cdynamicallocation

C dynamic allocation for a grid when rows are not known


I am trying to allocate a array of char*'s in C. I know the number of columns in advance, but not the rows and I want to allocate the rows as and when needed.

I tried to use:

char *(*data)[NUMCOLS]; //declare data as pointer to array NUMCOLS of pointer to char

data = malloc(sizeof(char*));

now, the above line should allocate for data[0] ... correct? then, I must be able to use the row like

data[0][1] = strdup("test");
 .
 ..
data[0][NUMCOLS-1] = strdup("temp");

I am getting seg fault. I am not able to understand what is wrong here. can anyone please help.


Solution

  • I would do this:

    #include <stdlib.h> 
    #include <stdio.h> 
    #include <string.h> 
    
    int main(){
      char ***a = NULL;
    
      a       = realloc( a, 1 * sizeof(char **) ); // resizing the array to contains one raw
      a[0]    = malloc(     3 * sizeof(char  *) ); // the new raw will contains 3 element
      a[0][0] = strdup("a[0][0]");
      a[0][1] = strdup("a[0][1]");
      a[0][2] = strdup("a[0][2]");
    
    
      a       = realloc( a, 2 * sizeof(char **) ); // resizing the array to contains two raw
      a[1]    = malloc(     3 * sizeof(char  *) ); // the new raw will contains 3 element
      a[1][0] = strdup("a[1][0]");
      a[1][1] = strdup("a[1][1]");
      a[1][2] = strdup("a[1][2]");
    
      for( int rows=0; rows<2; rows++ ){
        for( int cols=0; cols<3; cols++ ){
          printf( "a[%i][%i]: '%s'\n", rows, cols, a[rows][cols] );
        }
      }
    }