A pointer is used to store the address of some other variable.
So far, we have seen, how can we declare a variable.
And for every variable there is a memory location. The same way the house you live in has an address, the same way, the memory location of a variable also has an address.
Say for example, when we create an int type variable,
int num = 5;
The variable num has an address, Say the address of num is 1087(Just for our understanding). So, the actual value 5 resides in the address 1087.
int num = 5;
Now, what if you want to declare a kind of variable that would hold the address of the variable num.
And this is exactly where pointer type of variable comes into picture.
A pointer variable would hold the address of some other variable.
int *numPtr;
A Pointer type variable declaration would be just like a normal variable declaration. The only additional thing is, you need to put an asterisk * before the variable name.
Sounds little complicated? Let's simplify with the below example.
class MyApplication { static unsafe void Main(string[] arg) { int num = 5; int *numPtr; numPtr = # System.Console.WriteLine("The value is : "+ *numPtr); } }
So, in the above code, we have declared a variable num and assigned the value 5 to it.
int num = 5;
Let us say the address where num variable resides is 1087.
Now, we declare a pointer type variable that is going to hold the address of the integer type variable num.
int *numPtr;
So, just remember, the int of int *numPtr is the data type of the variable num.
In the next line, we are assigning the address of num(i.e. 1087) to the pointer type variable numPtr.
numPtr = #
Again just remember, &num gives the address of num.
Now, in other words, we can say that the pointer type variable numPtr is pointing to the value of num, i.e. 5.
And to print the value 5, we can use asterisk * followed by the pointer variable name (i.e. *numPtr).
And that's what we have done in the next line.
System.Console.WriteLine("The value is : "+ *numPtr);
And we get the below output.