Published by
Apr 6, 2009

C++ Pointer Basics (Part 1)

Score: 3.2/5 (10 votes)
*****
Note: While reading through this short overview of pointers in C++, you will find some
code samples that are given to help illustrate and document the concepts being
explained herein. Parts of code samples are not intended to be conclusive, compile
ready or free of type declaration or initialization errors.

If you've ever worked with shortcuts (Windows) or symbolic links (UNIX), you should
find pointers a relatively easy concept. There are references and then there are
pointers (which looks at the value being referenced). Though very similar in context,
there is a slight distinction between the proper usage and interpretation of references
and the proper usage and interpretation of pointers.

To illustrate this point, if you can imagine having a shortcut on your desktop in
Windows. This shortcut can be considered a pointer as it "points" directly to the
target file itself. A reference would then be the actual location (or container)
of our target file, similar to a mailing address (i.e. where can we find our target?)

When working with pointers, there are two operators with very specific functions
to keep into consideration:

REFERENCE: The first is the ampersand (&) which precedes an existing
variable or function and returns its actual address (reference) in memory.

For example:

1
2
3
4
5
char * varAuthor = "Matt Borja";

// a pointer (*) to another pointer (*), or simply **
char ** address_varAuthor = &varAuthor;
printf("Memory address of varAuthor: %x\n", address_varAuthor);


POINTER: The other operator is an asterisk (*) preceding our address variable, returning the
value pointed to by a reference.

For example:

 
printf("Value found at this memory address: %s\n", *address_varAuthor);


Keep in mind that it is important to observe data types as they must be treated
the same as standard variables in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
	// declare char type varAuthor
	char * varAuthor = "Matt Borja";
	
	// reference variable addr_varAuthor of our original varAuthor
	char ** addr_varAuthor = &varAuthor;
	
	printf("Value of our original varAuthor is %s.\n", varAuthor);
	printf("Address (reference) of our original varAuthor is %x.\n", addr_varAuthor);
	printf("Value (pointer) of our address (%x) is %s.\n", addr_varAuthor, *addr_varAuthor);
	printf("Get it?\n");
	return 0;
}