Search code examples
cfunction2dmallocallocation

2d dynamic allocation


I want to allocate dynamic an array of chars. So i ve the above code

      void initialize(char **document_table, int size){

      int x, i, j, M;

      printf("how many words every line: ");  scanf("%d", &M);

     document_table = malloc(sizeof(char) * size);
     for(x = 0; x < size; x ++) {
     document_table[x] = malloc(sizeof(char) * M);
      }


     for(i=0; i<N; i++){
    for(j=0; j<N; j++){

        scanf("%c",&document_table[i][j]);   
     }
      }
      }

but it seems that after the allocation of the memory the function stop working.


Solution

  • The declaration document_table = malloc(sizeof(char) * size); should have sizeof(char*), since a 2D array is an array of pointers to 1D arrays.