Pointers and Pass by Reference

Posted on April 18, 2013. Filed under: C++ | Tags: |


Same as C, C++ can access variable memory address with pointer.

& is reference operator, which get the memory address of a (whatever type) variable.

* is dereference operator, which get the value of a pointer variable.

int fish =5; //declare a int variable

int *fishpointer;//declare a pointer variable
fishpointer = &fish;//assign the memory address of int variable fish to pointer variable fishpointer. &fish get memory address of int variable fish.

*fishpointer=10;//put 10 as the value stored in the memory address, which pointer variable fishpointer points to.

We can pass a variable to a function by reference. The following example, we pass the memory address of a char variable fish to function passByReference, the function put value 10 to the memory address of the char variable fish. The memory address or reference of char variable fish is passed as a parameter to the function, by a pointer variable fishaddress.

char fish = ‘a’;

passByReference(&fish);

void passByReference(int *fishaddress) {

*fishaddress=10;

}

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: