C++ Pointers - Explain Concept In Detail
Declaration: int *p;
Here 'p' is an identifier that is used to store some address. The content of this memory address will of type 'int' as we mentioned in the declaration. We use any other data type also as per the type of content to be stored.
So the content of the p will be integer type not p itself.
Lets take an example.
int a=5; int *ptr; ptr=&a; //ptr now refers to the address of 'a' cout<<ptr; //it'll print the address of 'a' in hexadecimal code cout<<*ptr; //it'll print the contents of a ie value of the variable a.So now if we do:
ptr=ptr+1; cout<<ptr;The result is that the pointer variable 'ptr' will be incremented as:
ptr=ptr+(1*size of int)
ie initally if ptr was refering to the memory address say 1000, now it'll refer to the memory address 1002 because size of int is 2 bytes. Here we have added the size of int because our ptr stores the integer value.
Had it stored a float or some other value, we would had used the size of float or the appropriate data type instead.
So now we come to know that we can increment or decrement address value using pointers. But we can increment, decrement or even multiply pointers only with integer values no matter what type of data is stored in it.