For the programming beginners pointer is a nightmare. But it is not difficult at all. It’s just a kind of data type like everything else. But slightly a tricky one. So, let’s get dive into the pointer:
Pointer is any kind of data type like int, char, string etc.
Just have a look into this:
int p; //here we are declaring p variable which can hold any integer number or any integer type variable.
int a = 9;
p = 87;//allowed because it’s a integer number
p = a;//allowed because a is a integer type variable
now let’s declare a pointer:
int* p; //declaration of a pointer variable which can hold the address of any variable of integer type or any integer-pointer variable.
p = &a;//allowed because p is containing the address of a
p=b;//allowed because p is containing another integer-pointer type variable
De-referencing is another key concept regarding pointer. De-referencing is allowed only for pointer type variable. De-referencing means accessing the value of a particular address. De-referencing is done with the variable name preceded by asterisk(*) symbol.
int a = 9;
p = &a;
cout<<*p;//will print 9, because p is a int-pointer type variable which holds the address of int-variable a and de-referencing p is providing us the value stored in the address of a.
To understand the pointer keep in mind that:
- We can assign a variable to another variable if their types are same.
Explanation: You can assign int variable to another int variable, int-pointer variable to another int-pointer variable, char-pointer variable to another char-pointer variable. But you cannot assign int variable to int-variable,char variable to int-pointer variable or vice-versa.
2. Declaration of a pointer variable is associated with a variable type, asterisk(*) symbol and a variable name.
Explanation: type* p; //declaration of pointer variable.
3. Dereferencing is allowed only for pointer variable and it is associated with a asterisk(*) symbol and a pointer-type variable.
int a = 5;
p = &a;
cout<<*a; // compilation error because a is not a pointer-type variable
cout<<*p; // prints 5
You can keep in mind this formula to understand the basic concept of pointer:
variable= &var;//&var means the address of the var
(*variable); // dereferencing;
variable = v;
Every statement of the given formula is allowed. If you are beginner at coding and your program gets messed up with pointers just keep that formula in your mind and solve the complexity.
Happy Coding (* ! *)….