1/10/2012

NCC Tutorial: Pointers 4

In NCC Tutorial: Pointers 3, we learned that the arrays are pointer equivalents. Now we will see why the pointers are useful in function calls.

The easiest way is through a simple example. Imagine you need to swap the values of two variables. Say, a to take value of b, and b to take value of a. We will write a function 'swap', which will take two ints, 'a' and 'b', and swap their values. The code should be something like this:
void swap(int a, int b);
{
  int p = a; a = b; b = p;
}
It should work. 'p' takes value of 'a', then 'a' takes value of 'b', and then 'b' takes value of 'p', which is the previous value of 'a'. Compile, run... Doesn't work? Why?

The answer is: it doesn't work because C takes function arguments as copies. What I meant to say is, when you pass 'a' and 'b' to the function, only their values are passed, not references to the original 'a' and 'b'. So, when the function is over, only local 'a' and 'b' are changed, and the original ones stay the same.

And that's where the pointers come to save the day!

If you pass memory addresses instead (actually, copies of values of pointers are memory addresses ;)) and then you work exactly with them, you will have desired effect. When you copy value of a variable to the exact memory location where the other variable is stored, the new value will be saved.

So, instead of passing ints, you should pass int pointers, like this:
void swap(int *a, int *b);
{
  int p = *a; *a = *b; *b = p;
}
Now compile and run. If it works, you're doing great. Doesn't work? Why?

Probably you passed ints instead of their addresses. When you redefine swap function this way, remember to change the function call in main function. If it was like
swap(i, j);
now it should be saying
swap(&i, &j);
As you can see, if arguments in your function are pointers, you need to pass them addresses. You can use referencing operator for that.

That (with parts 1 - 3) is probably all the basic stuff you should know about pointers. Next time there will be some examples with all the techniques learned in this complete tutorial. Stay tuned, and 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!