1/07/2012

NCC Tutorial: Pointers 3

In NCC Tutorial: Pointers 2, we used pointers to directly access some variables in memory. That does not make much sense when we use them inside the main function, but will become clearer next time when we are going to use pointers as function arguments. Meanwhile, let's see why pointers are important for arrays.

Suppose we have an array of integers defined, and an int pointer:
int a[10], *p;
Now, you know that a[0] is the first element, and a[9] is the last (in this case). But what is a for itself? In the end, what does int a[10] mean?

For now we know that declaring a variable is actually telling the computer to take up some space and assign that space to the variable name, as we declared it. Declaring arrays is not so much different. If you declare an int array like in this example, you tell the computer to take up continuous place for 10 ints and assign it to the variable "a".

Values stored in the array cannot be read without index (the number in brackets). But what is actually got if you use just "a" without brackets is the beginning memory address from where all those values from the array "a" are stored. Sounds familiar? It should.

According to this, you might wonder if you could assign the value of "a" to "p". Your answer is: Yes, of course you can! Why? Because "a" is nothing else but a pointer.

Can you write p[8] after that and get the value of a[8]? Oh, sure you can. What else can you do? Well, if you increase p by one and then try to get value stored at p, you should get a[1]. Actually, you could iterate the whole array by just increasing the value of p.

And what if you write *a? Your guess is right - you will get a[0].

You wouldn't believe it, but you may write *(a+2) and actually get a[2]. This is somehow weird, but is really logical when you better look at it.

For those crazy freaks who now wonder if it is commutable, the answer is, again, yes. But you shouldn't try this if you don't want to confuse a noob. You see, it's completely logical too:
a[2] = *(a+2) = *(2+a) = 2[a]
As simple as that :)

Now you saw what arrays really are in C - nothing but pointers to just a little bigger parts of memory. I don't know if this is clear enough, but you should experiment and see for yourself. If you have any questions or comments, feel free to post them here. We'll see why pointers are yet more important in NCC Tutorial: Pointers 4. Hint: functions would be so lame without them. Keep on coding!

No comments:

Post a Comment

If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!