Sunday, 3 April 2011

The Basics of Pointers - Part 1

Now, we've learned to deal with variables. In most programming languages, you'll be able to deal with "references" to variables (more of why we would want to do this in the next post), such a thing in C is called a pointer. Let's just jump right into the code, shall we?

int x;
int *ptr;

Here, we are declaring an integer called x, and after that, we declared what is called "a pointer to integer". A pointer is declared by specifying the type, and then putting an asterisk before the desired identifier. Note that both of the following are correct syntax which do the exact same thing.

int *ptr1;
int* ptr2;

It doesn't matter is the asterisk goes before or after the space.

Last time, we learned about memory addresses. Basically, a pointer can be thought of as a variable which holds a memory address of a specific type of variable. Remember how we used "&" to access the memory location of a variable? Well here's where it comes into play. Let's say we have:

int x=5;
int *ptr;
ptr = &x;

This would make ptr point to x. In a way, this means that we can indirectly access the content of x. To do this, we put an asterisk in front of the pointer's identifier. For example, using the code above...


Result: 5

In the same way, we can modify the content of x by using the pointer.

*ptr = 42;

Result: 42

By putting the star in front of your pointer's identifier, it is like saying: "The content of..."

Note that in order for a pointer to work properly, it must be declared properly as well. By this, I mean that you cannot reference a float from a pointer to integer. This:

float y;
int *ptr3;
ptr3 = y;

will cause a compilation error. Why?

When you declare variables, bytes of memory are taken up. The amount of bytes is determined by what type of variable it is. An integer will typically take up 4 bytes, while a floating point number will take up 8. This means that when we have a pointer to integer, the pointer is expecting a memory address such that 4 bytes after it are taken up. In this example, it sees that it would need 8 bytes, that is, a pointer to integer would only hold half the data, and would be full after "filling up" half way. The compiler sees that this is a problem, and reports and error.

So we know about using pointers now. Great. So why would we ever want to do this?
Stay tuned.


  1. wow i'm learning to program better already

  2. okay, i've never heard of pointers so now im going to search for them in Java so i can make better programs.

  3. this makes so much more sense compared to the last post...