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)?
- A. int **m = malloc(rows * cols * sizeof(int));
- B. int m[rows][cols] = malloc(rows * cols * sizeof(int));
- C. int (*m)[cols] = malloc(rows * sizeof *m);
- 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
- With 4-byte int, what is printed? c int a[4]; memset(a, 1, sizeof a); printf("%d", a[0]);
- What is printed? c struct N { int v; struct N nx; }; struct N c = {3, NULL}, b = {2, &c}, a = {1, &b}; struct N prev = NULL, cur = &a, nx…
- After this code, what does buf hold and what is n? c char buf[20]; int n = sprintf(buf, "%04d|%.2s", 7, "xyz");
- What is printed? c int c = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (j == i) continue; if (j > i + 1) break; c++…
- Which of the following is NOT allowed in C?
- What is printed? c int cnt(int n, int last) { if (n == 0) return 1; return cnt(n - 1, 0) + (last ? 0 : cnt(n - 1, 1)); } int main(void) {…