This is a really confusing interview question for beginners. I have tried to explain it here in detail.
Question: Why do we get an error within this pointer declaration when I try to deference ‘p2’ ?
int main( )
int * p1, p2;
int a, b;
a = 6;
b = 7;
p2 = &b;
printf( “%d”, *p2 );
Answer: In the above program, there is no problem with the pointer declaration. The problem is – we are trying to dereference a non-pointer ‘p2’. Yes. Let us first understand the below declaration.
int a, b;
Here, both variables ‘a‘ and ‘b‘ are considered as ‘int‘ data types. whereas, here,
int * p1 , p2;
only ‘p1‘ is a pointer of type ‘int *‘, where as ‘p2‘ is just an ‘int‘. When ‘p2’ is not a pointer, then, obviously, ‘p2‘ cannot be dereferenced. And that is the reason, in the printf statement, the compiler throws an error message. The problem is that, we assume, both ‘p1‘ and ‘p2‘ become integer pointers with above declaration statement. This is a wrong assumption. If we wish to make even ‘p2’ as a pointer, then, the declaration statement should look like below.
int *p1 , *p2; // Here both ‘p1’ and ‘p2’ are of type ‘int *’. Both are pointers.
With this change in the above program, the compiler compiles the code perfectly fine.
Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.