Discussion
Pick out the output
#include <stdio.h>
void foo(void);
int main()
{
foo();
return 0;
}
void foo(void)
{
int i = 10, k = 10, j = 2;
int *ary[2];
ary[0] = &i;
ary[1] = &j;
printf("%d\n", ary[0][1]);
}
Answer: D
Correct answer: Undefined Behaviour
The array ary holds two pointers: ary[0] points at i and ary[1] points at j. Now read the expression ary[0][1]. Subscripting is defined as x[n] meaning *(x + n), so this is *(ary[0] + 1) - take the pointer to i, step one int past it, and read what is there. But i is a single int, not the first element of an array, so there is nothing legitimately one step past it. The standard permits forming a pointer one past a single object but not dereferencing it, and that makes this undefined behaviour. In practice the program will usually print whatever happens to sit next on the stack - often 10, the value of k, since many compilers lay these locals out adjacently - but that is an accident of the compiler and the optimisation level, not a result the language guarantees. It will not print 20, and it is neither a compile error nor a diagnosed runtime error, because nothing in the code is ill-formed and nothing traps. The listing in this record had lost the declaration the call in main depended on, and gave foo a parameter with the same name as one of its own locals; it is repaired above so that the program compiles and exhibits exactly the behaviour the question is about.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development