I just had to come up with a short, "real world" example of when and how pointers are used. What I don't like at all are examples like these:
int i = 4;
int* p = &i
*p = 2;
// i is now 2
So question #1 is: What do you think is a good, SHORT example (fits on one slide) that demonstrates the use of pointers?
My answer is... finding a character in a string :)
Question #2: How would you implement that, so that the program demonstrates important features of pointers?
My answer is...
// SPOILER ALERT
// scroll down to read my solution
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
// ...
int index_of(char c, char* string)
{
for (char* p = string; *p; ++p)
if (*p == c)
return p - string;
return -1;
}
Yes I know, it should be const char* instead of char*, but that's not the point here.
I like this version because it shows pointer arithmetic with ++p and p - string, but what I miss is the usage of the address-of operator &.
So, can you come up with other interesting examples?