How does pointer work ?

Thread Starter

Parth786

Joined Jun 19, 2017
642
If you want to print the address of 'var', then print the address of 'var', not the address of 'ptr'.
I always confuse when I have to select one option. Can you tell me condition where only pointer will be used. I want remember forever use of pointer . What can pointer do, which other can not do in programming. .
 

WBahn

Joined Mar 31, 2012
32,840
Just remember what a pointer IS. It is a variable whose value is meant to be interpreted as an address in memory.

The address operator (the ampersand used in a context that can't be interpreted as a bitwise AND) is an operator that returns the address at which it's operand is stored. So

&fred

is an expression that evaluated to the address at which the variable named 'fred' is stored.

The dereference operator (the asterisk used in a context that can't be interpreted as multiplication) is an operator that returns that value stored at an address. So

*fred

first evaluates the expression 'fred', which evaluates to the value stored in fred. It then uses that value as an address and fetches the value stored at that address. But to do this, it needs to know how many bytes to use and how to interpret them, which it does based on the kind of pointer that 'fred' is. This is why you can't dereference a void pointer without type casting it.
 
Top