The classic example for pointers is
I was going to post exactly this example for Simon, but you beat me to it.
but I'll annotate it for him.
char* strcpy( char* to, char* from){
char* ptr;
ptr = to;
This is subtle. We create the temporary pointer
ptr so we don't destroy our
to variable.
while( *from ){
The loop continues as long as
*from is true. What does that mean?
Remember this is a string copy function. Strings in C are just an array of chars. The convention is that strings are always null-terminated; that is, the last byte in the string is always '\0', which has a numeric value of zero. And also in C, any integer which is zero is considered false, any non-zero value is true.
Now, remember,
*from dereferences the pointer
from. That is, it returns the value in the location pointed to by
from. If the original string whose address is sent to the function (in
from) is ABCD\0 then each time through the loop *from will be 'A', then 'B', then 'C', then 'D', then 0 (not the ASCII '0', the value 0). The first four are non-zero, therefore true, and the code in the loop executes and then we go back to the test. When
*from is 0, that's false, so the loop exits.
*ptr++ = *from++;
}
This is classic C. Here's what happens. Note the precedence: the pointer dereference * is done before the post-increment ++.
*from is dereferenced, and you get a character (in example above, 'A', then 'B', etc). That character is put in the memory location pointed to by
ptr.
Then the two pointers
ptr and
from are incremented.
Then the while() case is evaluated again, now using the new thing returned when
from is dereferenced.
*ptr = 0;
This null-terminates your destination string. Remember that the code in the loop incremented ptr after the character copy, so it is "looking" at the next place you can put a character. In this case, that next character is the terminator \0 and the string copy is done.
return to;
}
The function has a
char* return type, so it returns our result, a pointer to a character. In this case, we know that it is a pointer to the first character in a string.
to is passed to us as a pointer to the destination string (assume that space for it exists, this function cannot know if that is true).
Remember at the start when we did the
ptr = to
? We saved the destination pointer. If we had, instead, incremented
to each time through the loop, when we returned it we would have sent the address of the last character in the string -- the null terminator. That's not useful, which is why we copied that address to a temporary and use the temporary for the copy and pointer increment.
This is really the most basic use of pointers, and if you grok this, you'll understand how pointers are generally useful.