Functions and Pointers
We can use pointers when passing parameters to functions. Remember how when we use scanf() we must type the '&' sign before the variable? This is because scanf() uses pointers, if you don't pass the parameter as a memory location it crashes.
Consider this program that swaps two numbers around.
Run it, it doesn't work. Normally with functions we define our own variables within the function and then return the values into variables in the main function. We don't have to do that, we can use pointers to directly access the address in memory of our variables. Remember, a pointer points to the address in memory of a variable, it points to the data stored for that variable. Consider the below code:
Notice we're using pointers now. Let's go through what happens.
In our main function we define our variables and give them a value. We then call swap_nums(), only this time we pass (&a, &b). We're passing the function the addresses in memory of the variables a and b, not their actual value.
Now we define our pointers for our function. Remember, we passed the function our variable's addresses, so it makes sense we use pointers that now point to our variables. We then do the swap:
Let's go through this and explain it step-by-step:
Define an integer named extra.extra = *a;
Pass the value pointed to by *a to our variable. So now extra contains the value of a from the main() function. The *a in our function is a pointer, we use it to directly access the memory and load the value of a into extra. We assigned 5 to a, so now extra contains 5.
*a = *b;
Load the value pointed to by *b (7) into *a, so now *a contains the value we assigned to b in our main() function, a contains 7.
*b = extra;
Load the value in extra (5) into the variable pointed to by *b. B points the the address in memory of b from the main() function so we are infact loading 5 into b.
The values have been swapped, we used pointers to access the memory addresses of the variables and manipulate the data contained within them. This is an example of the power of pointers, they allow you to work at a "lower" level.
So when you're using scanf() and you have to do scanf("%d", &num);, this is why, the scanf() function wants the address in memory of the variable so it can laod the data into it, you must give it the address in memory or your code will crash. Now you know why you need to do this, and hopefully that example explained pointers a little more to you. Pointers are used extensively in C, they make code more efficient, learn to use them.
That concludes our introduction to C programming. I've tried to cover the basics of C. The difficult part of programming is getting started, hopefully this tutorial did that for you, you can put together the information you have learned here and think up your own ideas. Search the internet for information you need, learn how to use C to its maximum potential -- stick with it and you will.
No Comments for this page.