What would be the output for the following Turbo C code?
#include<stdio.h>
void main()
{
int a[]={ 1, 2, 3, 4, 5 }, *p;
p=a;
++*p;
printf("%d ", *p);
p += 2;
printf("%d", *p);
}
#include<stdio.h>
void main()
{
int a[]={ 1, 2, 3, 4, 5 }, *p;
p=a;
++*p;
printf("%d ", *p);
p += 2;
printf("%d", *p);
}
A. 2 4
B. 3 4
C. 2 2
D. 2 3
E. 3 3
Answer: Option D
Join The Discussion
Comments ( 5 )
Related Questions on Pointer
In C, what is a pointer primarily used for?
A. Decision making
B. Code organization
C. Variable declaration
D. Storing values
In C, how do you declare a pointer variable that can store the address of an integer?
A. int *ptr;
B. ptr int;
C. int ptr;
D. ptr *int;
What is the purpose of the '->' operator in C when used with pointers?
A. Arithmetic operation
B. Indirection operator
C. Member access operator
D. Bitwise operation
It is printing 3 because is as follows :-
p = a; //address of a is stored in p
*p++ //incrementing the value inside that address (not the address).
//(*p = *p+1) //1+1 = 2
printf(*p) // 2
Now,
p = p + 2
//here p contains the address not the value inside that address so (p = a)where a was at 0 location
p = 0+2 = 2 its a location so
it will print a[2]
printf(*p)//we are value of p at location 2 thats why it will print 3.
op:-(2,3)
here firstly the value of p* is 2 and value of p is the value of a
so value of p is 1 and p* is 2
now p=p+2
hence p=1+2=3
hence the ans is 2 and 3
here *p is different from p .so, at first we had incremented p*, then we had incremented p.so when we print p* variable at 1st time it gives out put as 2 and 3.
The solution is :
2 3
not
3 3,
because ++*p is interpreted as ++(*p) and increments value of a[0].
please explain this problem in a more effective way!
couldn't understand the solution