Simple pointer example

Hi,

The following is a simple (I think!) example of the use of pointers...

1
2
3
4
int &variable1Label = variable1;
    variable1Label = 101;
    cout << "The value of integer1 after assigning a value "
    << "to the label is now: " << variable1 << endl << endl;


I'm not really understanding it, though. How does it actually work? I have referred to the tutorial on this site, but am still unsure.
This is an example of references, not pointers.
variable1Label will have access to the same part of memory which was taken by variable1 so, by modifying variable1Label you will also modify variable1
Pointer syntax:
type *name

A pointer is a variable that point to an adress in memory.

Say you make a variable of type int:
int var = 10

Now you make a pointer and make it point to 'var':

int *pvar = &var //& is the adress operator

Now 'pvar' contains the adress of 'var' (or 'pvar' points to the adress of 'var')and through 'pvar' you can change 'var':

*pvar = 15

If you wanted to print 'var' it would print 15 instead of the initial 10.

Another example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void double_it(int *p){
*p = *p * 2;
}


int main(){

int var = 10;
int *pvar = &var;

cout << *pvar <<endl; //prints 10
double_it(*pvar);
cout << *pvar<< endl;//prints 20
cout << var << endl; //prints 20 also, because we changed the object *pvar pointed to.


If on the other hand we tried this function with 'var' as the argument:
1
2
3
void double_it(int n){
n = n*2;
}


And then wanted to print 'var':
 
cout << var<<endl;


It would print 10 because this function does not change 'var', only a copy of it and that copy never gets returned, so this does not work.





Last edited on
Line 12 should be :
double_it(pvar);
Topic archived. No new replies allowed.