ProgrammingVery hardProduct company OA · GATE CS

In C99, which declaration lets you allocate a rows × cols matrix of int (cols known at run time) with ONE malloc, use it as m[i][j], and release it with ONE free(m)?

  1. A. int **m = malloc(rows * cols * sizeof(int));
  2. B. int m[rows][cols] = malloc(rows * cols * sizeof(int));
  3. C. int (*m)[cols] = malloc(rows * sizeof *m);
  4. D. int *m[cols] = malloc(rows * sizeof(int));

Correct answer: C. int (*m)[cols] = malloc(rows * sizeof *m);

m is a pointer to a (variable-length) row of cols ints, so sizeof *m is one row and m[i][j] scales correctly. int ** would read the ints as row pointers; the last two try to initialise arrays from a pointer, which does not compile.

More C Programming questions

Exams that ask this topic