0

can you explain to me why i have a segmentation error?

#define M 5 

char ** test(int size) {
    char ** grid = malloc(size * sizeof(char)); 
    for (int row = 0; row < size ; row++) {
        grid[row] = malloc (size * sizeof(char)); 
    }

   for (int i = 0 ; i < size ; i++) {
       for (int j = 0 ; j < size ; j++) {
           grid[i][j] = 1; 
       }
   }
    return grid ; 
}

int main()
{
    char ** grid = test(M);  
}

Yet it seems correct to me...

  • What line s the seg fault? – nicomp May 08 '21 at 11:23
  • 1
    char ** grid = malloc(size * sizeof(char)); should be a pointer to an array of pointers, not a pointer to an array of chars. sizeof(char) should be sizeof(char *) – nicomp May 08 '21 at 11:28

1 Answers1

-1

you want

  char ** grid = (char**)malloc(size * sizeof(char*)); 
Pierre
  • 34,472
  • 31
  • 113
  • 192