Playing with C++ – Pointers

Posted on Updated on

I dreaded pointers for a very long time and still kind of do because of how tricky they are to understand. For practice, I wrote the program below (based from this tutorial http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm):

#include <iostream>

using namespace std;

pointer_test::pointer_test() {
	// constructor
}

pointer_test::~pointer_test() {
	// destructor
}

int main() {
	int var = 20;	// pointer value
	int *ip;		// pointer reference

	ip = &var;

	cout << "Value of var variable: " << var << "\n";
	cout << "value of ip (pointer by reference): " << *ip << "\n";
	cout << "ip (pointer by reference): " << ip << "\n";

	return 0;
}

When executed:

900586-m@benjamin.lo% g++ pointer_test.cpp
900586-m@benjamin.lo% ./a.out
Value of var variable: 20
value of ip (pointer by reference): 20
ip (pointer by reference): 0x7fff4ff65828

What I now understand is that:

– &var will point to the value of what the pointer has as its value.
– ip will also point to the value of what the pointer has as its value (same as above), but, ip’s value is not really defined but is actually referencing to the var pointer’s value.

– *ip will assign its memory address as its value (which is the address of var’s value)

Cool, Hopefully this was easy enough for me to remember later.

Advertisements

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