C program is given below: # include <stdio.h> int main () { int i, j; char a…
2008
C program is given below:
# include <stdio.h>
int main ()
{
int i, j;
char a [2] [3] = {{'a', 'b', 'c'}, {'d', 'e', 'f'}};
char b [3] [2];
char *p = *b;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
*(p + 2*j + i) = a [i] [j];
}
}
}
/* Add code here. Remove these lines if not writing code */
What should be the contents of the array b at the end of the program?
- A.
a b
c d
e f
- B.
a d
b e
c f
- C.
a c
e b
d f
- D.
a e
d c
b f
Attempted by 7 students.
Show answer & explanation
Correct answer: B
Key idea: the pointer p is set to *b (the address of the first row), so p behaves like a linear char pointer into b. Each assignment uses index = 2*j + i, and in the 3x2 array b the linear index maps to b[row][col] where row = index / 2 and col = index % 2.
For i = 0, j = 0: index = 2*0 + 0 = 0 → b[0][0] = 'a'
For i = 0, j = 1: index = 2*1 + 0 = 2 → b[1][0] = 'b'
For i = 0, j = 2: index = 2*2 + 0 = 4 → b[2][0] = 'c'
For i = 1, j = 0: index = 2*0 + 1 = 1 → b[0][1] = 'd'
For i = 1, j = 1: index = 2*1 + 1 = 3 → b[1][1] = 'e'
For i = 1, j = 2: index = 2*2 + 1 = 5 → b[2][1] = 'f'
Final contents of array b (each row):
Row 0: ['a', 'd']
Row 1: ['b', 'e']
Row 2: ['c', 'f']