Pointers

If you are new to C or C++ programming, you may be perplexed by your first encounter with a pointer. What is it good for, how do I use them in my own programs, and what do they actually do? These things aren't always easy to understand, but this tutorial will shed some light on the subject.

What is a Pointer:

A pointer is just an address indicating to the program a location in memory. This location could point to anything, but thanks to C and C++'s strong typing you'll know what it points to when you're programming. You can think of a pointer like a signpost that tells your program where to look in RAM for the variable you're referring to, and you can think of addresses like a numbered list of home addresses going from 0 on up. The figure below is a pictographical representation showing this relationship between pointer and value.

Pointer Image

As you can see, the pointer itself contains an address in memory, and that address in memory contains a value. You'll soon learn that a pointer can point to another pointer, and why you'd want to do that, but all you have to envision is taking the above picture to that next level of indirection, an address referring to another address, that finally refers to a value.

Using Pointers:

Since a pointer is just an address, you can use it to point to values in your programs. So how would you get the value the pointer is pointing to? The magic word here is “dereferencing”, which tells the compiler you want the value the pointer is pointing to. This is easy to do, using the dereferencing operator (*). It's the same symbol for multiplication, but it's how it's used in context that matters. Below is a code snipped that dereferences a value and assigns it to an integer:

int myNumber = *otherNumber;

The syntax is quite simple, but it shows that pointers and non-pointers must be treated differently everywhere in your program. This includes some other different pointer syntaxes (including the arrow operator ”->”, but that's for later).

Arrays:

The easiest and most familiar use of pointers is when you learned about arrays, since an array is just a block of data pointed at by a pointer. Observe this simple C/C++ example below:

#include <stdio.h>
 
int main(void)
{
    /* myArray is just a pointer to five ints. */
    int myArray[] = { 1, 2, 3, 4, 5 };
 
    /* You can dereference myArray like a pointer, and get the first value */
    printf("%d", *myArray);
 
    return 0;
}

This shows that an array, just like a pointer, can be dereferenced to acquire it's first value. In fact, going through an array's contents is just the act of dereferencing, which tells the compiler you want the value the pointer is pointing to. There are several different syntax changes when using pointers, since pointer types must be treated differently from non-pointer types. Normally for arrays the above syntax is discouraged, but you should keep in mind that arrays are pointers, just pointing to statically declared memory. What this means is myArray[4] is the same as *(myArray + 4), but obviously the former is less confusing. Here's an image showing how pointers point to arrays in memory:

Array of values

Strings:

A string is an array of characters in C. You can set a string easily like so:

char string[]="This is a string!";

And then you can print it like this:

printf("%s\n", string);

The pic above is actually an example of a string, showing the string “abc” in memory. Because every character is an element of the array, you can handle all of the characters separately in a string. The last character in a string is always a 0, that is the NULL character '\0'. If there is a NULL character in the middle of a string, you will only see the first part of the string up until the NULL character. If you want to print the second character, it's as easy as this:

printf("%c\n", string[1]);

Just remember that array indices start at 0.

Passing pointers as parameters:

So now that you know what the asterisk is for, and one of the purposes of pointers is for arrays, how can you use this to help you? The second thing you can do with a pointer is, just like any other value, you can pass it as a parameter to another function. This, however, has the added benefit of making it so that function can now modify the contents of what was passed! To exemplify this, take a look at this example:

#include <stdio.h>
 
void changeToFive(int* change)
{
    *change = 5;
}
 
int main(void)
{
    int anum = 3;
    int* pointy;
 
    printf("anum = %d", anum);
    pointy = &anum;
    changeToFive(pointy);
    printf("anum now = %d", anum);
 
    return 0;
}

Address-Of:

You may have noticed this strange line in the above code:

pointy = &anum;

You can make pointers point to any variable you have already defined. To get the address of a variable, prefix it with the aptly named address-of operator (&). The above code assigns the address of anum to be pointed to by pointy.

The following code will assign a value of 54 to number, and have pointer point to number. It then prints the value of number by dereferencing it, and it prints the address that pointer points to.

#include <stdio.h>
 
int main(void)
{
    int number=54;
    int *pointer;
 
    pointer=&number;
    printf("pointer's address value is %p, and the value at that address is %d", pointer, *pointer);
 
    return 0;
}

Passing arrays as parameters:

Now that you know how to pass a pointer, and how to dereference arrays using the [] operators, you've almost got the basics of pointers! There's just one more thing to bring up, and it's how to pass an array itself as a parameter. Since you already know that an array is just a pointer, passing an array is identical to passing a pointer, except your receiving function treats it like an array.

#include <stdio.h>
 
void makeAllLetterX(char* array)
{
    for (int iii = 0; array[iii] != '\0'; ++iii)
    {
        array[iii] = 'X';
    }
}
 
int main(void)
{
    char string[] = "Hello Wordl!";
 
    printf("%s\n", string);
    makeAllLetterX(string);
    printf("%s\n", string);
 
    return 0;
}

Gotchas:

There are some problems with pointers that can make using them dangerous:

  1. If you attempt to dereference a pointer without assigning it a value, this results in, according to the C standard, “Undefined behavior”. Undefined behavior is the worst kind of behavior, since this essentially means your entire program becomes undefined, and thus buggy. This kind of pointer is also known as a “wild pointer”.
  2. Dereferencing a NULL pointer is equally dangerous, but doesn't result in undefined behavior. Instead, the C standard mandates that this results in a segmentation fault since by definition your program is broken.
  3. Obviously due to the above, passing a NULL pointer to a function that doesn't specifically document accepting NULL pointers or passing a wild pointer to any function is equally dangerous.

Other purposes:

Oh, and there's one more purpose behind pointers… perhaps the best reason for them at all, the reason some languages ONLY use pointers, the reason the languages designers put it there in the first place… dynamic memory allocation! C and C++ treat this field differently, but nonetheless both make use of pointers for dynamic memory. If you want to read more about that, there is a tutorial for C here.

In C and C++, pointers are a very important and useful part of the language. Understand how pointers work, and you will go far in C and C++!

This collaborative tutorial was brought to you by ZekeDragon and Guest.

 
pointers.txt · Last modified: 2010/01/09 15:43 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki