I'm new to programming and I'm trying to wrap my head around the idea of 'pointers'.
int main()
{
int x = 5;
int *pointerToInteger = & x;
cout<<pointerToInteger;
}
Why is it that when I cout << pointerToInteger;
the output is a hexdecimal value, BUT when I use cout << *pointerToInteger;
the output is 5 ( x=5).
Note that the asterisk (*) used when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator seen a bit earlier, but which is also written with an asterisk (*).
A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.
In computer programming, the dereference operator or indirection operator, sometimes denoted by " * " (i.e. an asterisk), is a unary operator (i.e. one with a single operand) found in C-like languages that include pointer variables.
C++ provides two pointer operators, which are Address of Operator (&) and Indirection Operator (*). A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to "point to" the other variable.
One way to look at it, is that the variable in your source/code, say
int a=0;
Makes the 'int a' refer to a value in memory, 0. If we make a new variable, this time a (potentially smaller) "int pointer", int *
, and have it point to the &a (address of a)
int*p_a=&a; //(`p_a` meaning pointer to `a` see Hungarian notation)
Hungarian notation wiki
we get p_a
that points to what the value &a
is. Your talking about what is at the address of a
now tho, and the *p_a is a pointer to whatever is at the &a (address of a).
This has uses when you want to modify a value in memory, without creating a duplicate container.
p_a
itself has a footprint in memory however (potentially smaller than a
itself) and when you cout<<p_a<<endl;
you will write whatever the pointer address is, not whats there. *p_a
however will be &a
.
p_a
is normally smaller than a
itself, since its just a pointer to memory and not the value itself. Does that make sense? A vector of pointers will be easier to manage than a vector of values, but they will do the same thing in many regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With