Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Pointers: What, How, and Why

realloc

  • Please log in to reply
21 replies to this topic

#1 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 01 December 2009 - 01:31 AM

*
POPULAR

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.
Posted 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:
Posted Image

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:
  • 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".
  • Dereferencing a NULL pointer is equally dangerous, and according to the C99 standard, also leads to undefined behavior.
  • 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. Any suggestions, questions, and positive feedback is welcome. As always, +rep is appreciated, just remember to give us both credit.

Edited by ZekeDragon, 08 February 2011 - 05:58 PM.

  • 12
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#2 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Programming Language:C

Posted 01 December 2009 - 01:41 AM

I hope you like our collaborative tutorial! If you choose to +rep ZekeDragon, make sure you +rep me too!
  • 9
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#3 Orjan

Orjan

    CC Mentor

  • Moderator
  • 2918 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#

Posted 01 December 2009 - 01:45 AM

did you create it through Google Wave? +rep
  • 0

I'm a System developer at XLENT Consultant Group mainly working with SugarCRM.
Please DO NOT send mail or PM to me with programming questions, post them in the appropriate forum instead, where I and others can answer you.


#4 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 01 December 2009 - 01:48 AM

did you create it through Google Wave? +rep


Yep, we both wrote it, using Google Wave. We started a wave to collaborate and edited it many times simultaneously.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#5 marwex89

marwex89

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 2857 posts

Posted 01 December 2009 - 07:16 AM

+rep to you both! Google wave it is ;)
  • 0
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#6 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 01 December 2009 - 07:33 AM

This is just impressive! You guys did an awesome job! +rep to both of you. If we had a tutorial of the month here, I'd vote for this one. :)
  • 0

#7 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 01 December 2009 - 08:27 AM

+rep to both for a very nice tutorial.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#8 Egz0N

Egz0N

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1155 posts

Posted 01 December 2009 - 08:32 AM

i like it .. +rep to both .. :)
  • 0

#9 Hignar

Hignar

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 239 posts

Posted 02 December 2009 - 05:09 AM

Nice work guys.

Any plans for a follow up on dynamic memory allocation in C++?
  • 0
If there's a new way, I'll be the first in line.

But, it better work this time.

#10 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 02 December 2009 - 06:25 AM

@Hignar: Absolutely, I even posted that in my other tutorial I just recently released: Getting Started with Classes. I need to update this one with that information and include the arrow operator since that was the intent behind doing this class and Guest's upcoming struct tutorial for C.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#11 arkanion

arkanion

    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 13 January 2010 - 11:59 AM

good question
  • 0

#12 hodge-podge

hodge-podge

    CC Regular

  • Just Joined
  • PipPipPip
  • 45 posts

Posted 16 January 2010 - 07:56 PM

So why should I use them? D: I don't understand why you would use them rather than just variables. Im sure there are some very good reasons, and things you can only do when using pointers, but I can't think of any.
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download