edited by
17,256 views
62 votes
62 votes

Consider the following program in C language:

#include <stdio.h>

main()
{
   int i;
   int*pi = &i; 
   
   scanf("%d",pi);
   printf("%d\n", i+5);
}

Which one of the following statements is TRUE?

  1. Compilation fails.
  2. Execution results in a run-time error.
  3. On execution, the value printed is $5$ more than the address of variable $i$.
  4. On execution, the value printed is $5$ more than the integer value entered.
edited by

5 Answers

Best answer
56 votes
56 votes
int i; //i is declared
int*pi = &i;  //pi is a pointer variable 
//and is assigned the address of i

scanf("%d",pi); //i is overwritten with the value 
//we provided because pi is pointing to i earlier

printf("%d\n", i+5) //it will print the value stored in i+5

input $=3;$ output $=8$

Option D is answer.

edited by
37 votes
37 votes
main()
{
   int i;//here i stores GARBAGE VALUE
   int*pi = &i; //p stores address of i
   
   scanf("%d",pi);// think like that scanf("%d",&i); because pi=&i; so we give value store at i(value at                  address)
   printf("%d\n", i+5);//if we give n output n+5
}
5 votes
5 votes
There is no problem in the program as pi points to a valid location. Also, in scanf() we pass address of a variable and pi is an address.

So answer is D
3 votes
3 votes
#include <stdio.h>
main()
{
    int i;
    int *pi = &i;  // pi pointing to address of i

    scanf("%d", pi); /*  means store the inputted value by scanf at location/address  pointed by pi. i.e at variable int i. earlier int i was holding garbage value. now it will store input value given by you. let say you input the  value of i=10;  */

    printf("%d\n", i+5);  //  add 5 in int i.  i.e 10+5 =15
}

so final output will be 5 more than entered value by you.
Answer:

Related questions

52 votes
52 votes
3 answers
2
Kathleen asked Sep 14, 2014
11,747 views
The most appropriate matching for the following pairs$$\begin{array}{|ll|ll|}\hline X: & \text{m = malloc(5); m = NULL;} & 1: & \text{using dangling pointers} \\\hline Y...
72 votes
72 votes
4 answers
3