If 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!
(written 2010-01-13 07:55:48)
Associated topics are indexed under
C207 - C and C based languages - Pointers and references [2670] Pointers to Pointers to Pointers - what is the point? - (2010-03-10)
[2005] Variables and pointers and references - C and C++ - (2009-01-23)
[1497] Training Season Starts again! - (2008-01-07)
[1478] Some new C programming examples - files, structs, unions etc - (2007-12-19)
[1155] Pointers in C - (2007-04-19)
C210 - C and C based languages - File Handling [2571] Reading and writing files in C - (2010-01-12)
[2002] New C Examples - pointers, realloc, structs and more - (2009-01-20)
Some other Articles
What does const mean? C and C++Sharing variables between files of code in C - externSummary of Wiltshire Core Strategy responsesC Structs - what, how and whyThe what and why of C pointersFunction Prototypes in CHow to run a successful online poll / petition / survey / consultationForums for your Melksham and open source discussionsExtra MySQL course dates (2 day course, UK)