Hello,
I am Sandeep Patil. I have one question about pointer in c and also c++.
What is function of pointer? it is address operator. We use pointer to store address of variable to refer that variable. Then why we use char pointer, int pointer as a different pointers. Why should we not use one type of pointer to refer all types of variable?
I would like to talk about why you can't have one kind of pointer for all variables. The answer has to do with address calculations. If you have pointer, ptr:
-
int* ptr;
-
int array[5];
-
ptr = array;
-
Here the address of element 0 (an int) is assigned to the int pointer ptr.
ptr = ptr + 2 tells the compiler to calculate an address that adds 2 times the sizeof an int to the address in ptr.
1000 array[0]
1004 array[1]
1008 array[2]
1012 array[3]
1016 array[4]
So the new address is ptr = 1000 + 2 *4
The sizeof(int) is 4.
That is, ptr now contains 1008 which is the address of array[2].
The compiler knows to use sizeof(int) because the pointer is a pointer to an int. If the compiler were to use any other value, like sizeof(char) or sizeof(double), then the calculated address for the array element will be wrong.
That is why the compiler is so picky about how you use your pointers.