Why do I get an error in this pointer declaration in C/C++ language ?

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’ ?

#include <stdio.h>

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.

Author Information:

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

 

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.