Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
530 views
in Information Technology by (115k points)

Consider the following ANSI C program.

#include<stdio.h>

int main(){

int arr[4][5];

int i, j;

for(i =0; i<4; i++){

for (j =0; j<5; j++){

arr [i][j] = 10 * i + j;

}

}

print("%d", *(arr[1] + 9));

return 0;

}

What is the output of the above program?


1. 14
2. 20
3. 30
4. 24

1 Answer

0 votes
by (114k points)
selected by
 
Best answer
Correct Answer - Option 4 : 24

code:

#include<stdio.h>

int main(){

int arr[4][5];

int i, j;

for(i =0; i<4; i++){

for (j =0; j<5; j++){

arr [i][j] = 10 +i + j;

}

}

print("%d", *(arr[1] + 9));

return 0;

}

  1. C doesn't check array boundaries. A segmentation fault will only occur if you try to dereference a pointer to memory that your program doesn't have permission to access. Simply going past the end of an array is unlikely to cause that behavior. Undefined behavior is just that - undefined. It may appear to work just fine, but you shouldn't be relying on its safety.
  2. Your program causes undefined behavior by accessing memory past the end of the array. In this case, it looks like one of your str[i] = c writes overwrite the value in i.

Explanation:

*(arr[1] + 9) can be written as arr[1][9].

as C doesn't follow bound check and follow the row major ordering

arr[1][5] = arr[2][0]  // arr[1][4] will be first row of array and then arr[2][0] will be second row of array 

arr[1][6] = arr[2][1]

arr[1][7] = arr[2][2]

arr[1][8] = arr[2][3]

arr[1][9] = arr[2][4]

arr[2][4] = 10*i + j = 10*2+4 = 24

Option 4 is the answer.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...