POINTERS IN CPP
Image Description : Any first year student studying pointers for the first time
and like there are only two weeks to go for the End Semester Examinations
To anyone reading this, without keeping in mind your semester or examination schedule just keep reading this for the next 10 minutes and believe me you'll start playing with pointers for the rest of your life, I promise!
First things first, to learn anything new you should always keep an open mind, like start exploring stuff, don't consider it to be a kind of burden, lets learn pointers now with the same energy and enthusiasm,
Okay, answer me this like we all know what a datatype is, don't we? Yes we do, like listing some basic ones of those, int, float, double and so on...
When you write:
int x =10;
double y =20.5;
So what is going on is that there's this variable x which is storing an integer type value i.e. 10, right!
Similarly, this variable y stores a double type value i.e. 20.5, right!
Similar to these datatypes, pointer is also a datatype which stores address, simple, that's it, don't overthink it,
Let us understand it with the help of a program:
/*
Before writing any piece of code, I just want to say that don't overthink about
pointers
Pointer is basically a datatype which stores address of the variable that it is
pointing to
Let me Explain it to you this way, when you write int x =10 , so basically you've
created a variable x of datatype int which stores an integer type value,
similarly when you write int* x , it basically means that x is a pointer pointing
to integer type value, that's it
PRO TIP: Start reading the pointer from right to left
x=variable
*=pointer
int=integer
right to left (x is a pointer to integer type values)
*/
#include<iostream>
using namespace std;
int main(){
int* p;
int b=10;
p=&b;
cout<<"The value of the variable is : "<<b<<endl;
//the above expression displays 10
cout<<"The address of that variable is : "<<p<<endl;
//the above expression displays 0x7bfe14
//lets play with the value ant try to change it
//dereferencing with *operator *(&b)
//in simple way you can consider like * and & cancel each other and we are
//left with b only
//NOTE: The above line is just to make you understand the concept
*p=20;
cout<<"The value after changing is : "<<b<<endl;
//the above expression displays 20
//look the address is still the same this means that still it is pointing to
// same location
cout<<"The address of that variable is : "<<p<<endl;
//the above expression displays 0x7bfe14 which is still the same
}
Great Explaination, thanks!
ReplyDeleteThank you so much Akshat, means a lot!
Delete