The what and why of C pointers
Archive - Originally posted on "The Horse's Mouth" - 2010-01-13 07:55:48 - Graham EllisIf you put a "*" in front of a variable name as you declare the variable in C, that variable holds the ADDRESS of a value of the type give, rather than the value itself. Thus:
int bill; /* holds an integer */
int *ben; /* holds an ADDRESS. At that address you'll find an integer */
You can then add a "*" in front of a variable name in your executable code to ask for "the contents of", and an "&" to ask for "the address of". What seems like a very simple thing to describe, though ...
a) Leads to a lot of diagrams and explanations on a course
b) Makes a lot of people ask "WHY do we do this?"
Firstly, I've put a sample program showing each of the elements in use, and with lots of comments line by line, [HERE].
Now ... "why" ...
1. If you pass an ADDRESS into a function, you get the ability to alter the value that it points to. If you just copy a value into a function (the default alternative), any changes you make are just going to be to the copy and won't get back to the calling code
2. It makes passing big structures and arrays into functions much more efficient - you just pass a single address rather than duplicating a lot of data
3. You can now pass back multiple parameters from a function
4. You can write common code using a pointer variable name like "current" and have it work on lots of different bits of data at different times, again saving recoding or copying
5. It lets you handle heterogeneous arrays, where the size of each element may in effect vary
6. It allow you to use dynamic memory allocation functions such as calloc and realloc to grab memory as you need it, rather than wastefully coding in such a way that arrays are always big enough to take the largest possible data set your program will ever use.
It's really incredible what a few "*"s and "&"s can do!