Pointers are just like normal variables. Like an
int
. All the rules for initializing ints... passing them to/from functions, etc... all of that works exactly the same with pointers.
The only difference is that pointers hold an address, rather than an integer.
Simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func(int foo)
{
cout << "foo is " << foo << endl;
foo = 5;
cout << "foo is now " << foo << endl;
}
int main()
{
int myvar = 1;
func( myvar );
cout << "myvar is " << myvar << endl;
}
|
foo is 1
foo is now 5
myvar is 1 | |
Here, 'foo' is being passed
"by value" to 'func'. That means it is a
copy. foo and myvar are two completely independent variables. When myvar is passed to the function, foo is being initialized with the contents of myvar. Like doing this:
Changing foo will not change main's myvar because foo is its own variable.
Pointers are exactly the same.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func(const char* foo)
{
cout << "foo is " << foo << endl;
foo = "5";
cout << "foo is now " << foo << endl;
}
int main()
{
const char* myvar = "1";
func( myvar );
cout << "myvar is " << myvar << endl;
}
|
foo is 1
foo is now 5
myvar is 1 | |
Notice how this behaves the exact same way. Changing 'foo' in func does not change 'myvar' in main because they are two entirely separate and independent variables.
The confusion comes from the fact that you can use a pointer's address to access another variable
So what does that mean?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void func(int* foo)
{
*foo = 5; // change the data the foo points to
foo = nullptr; // change the pointer itself
}
int main()
{
int var = 1;
int* ptr = &var; // ptr points to var
func(ptr); // pass 'ptr' to func
// here... ptr DID NOT CHANGE.. it is not null, even though
// func set ptr to null. This is because 'ptr' and 'foo' are two different
// variables.
// HOWEVER... 'var' DID change. var is now 5 instead of 1. Explanation below.
}
| |
Note that there are two different things we're dealing with with 'foo' here:
1) The pointer itself.
2) The variable that the pointer points to.
Since 'ptr' contains the address of (ie, "points to") 'var'... when it is passed to func, this means 'foo' will also contain the address of 'var'.
When we do this:
*foo = 5;
, we are not changing our 'foo' variable... instead we are looking at the address foo contains... going to that address in memory, and changing
THAT variable.
So since 'foo' points to 'var'...
*foo = 5;
will change 'var'.
Again note, however, that there is
nothing func can do here to change 'ptr' in main. You can do anything with 'foo'... and 'ptr' will remain unaffected.