Declaration of a pointer
int *p; int a=10;
int is not the datatype of pointer as pointer points to the address of the memory location. Therefore, it is the data type of the content stored at that address.
*p is how you declare the pointer. Just like you declare any other variable (say p as int p or a as int a), a pointer is preceded by an asterik (*). Note that ‘a’ is an integer type and ‘p’ is a pointer.
Assign value to a pointer
As we know & refers to the address when we use it before the variable name, Therefore this statement means get the address of ‘a’ and store it in ‘p’. It will not store the value of ‘a’ (which is 10) in p, In fact, it will store the address of ‘a’ in ‘p’. Now we can say that ‘p’ points to ‘a’. As shown below address of a is 1004 so p stores 1004 or it points to 1004.
Changing contents of variable using a pointer
Now if we want to change the value of ‘a’ using the pointer, we will do it this way:
This means set the value ’15’ stored at the address which is pointed at by ‘p’. As ‘p’ points to 1004, it will go to 1004 and update the value stored at that address i.e. update the value of ‘a’ to 15 which was 10 earlier.
Summing it up, the program looks like this:
int a=10; int*p; //a=10 p=&a; //p=1004, a=10 *p=15; //p=1004,a=15