I was recently reviewing an excellent, highly praised article on pointers: What are the barriers to understanding pointers and what can be done to overcome them? As I read through it, I came to understand what pointers are. Unfortunately, I'm still unable to use them.
Here's why: I don't understand the naming! Or the applications, really, of pointers. After reading through several 'so-you-want-to-learn-c' books and articles, I've encountered similar code, time and again: "how to create and instantiate a pointer".
When answering, please use example code to demonstrate what, in practice, pointers output.
Here's the code:
char ch = 'c';
char *chptr = &ch;
Or, perhaps more confusing:
char ch = 'c';
char *chptr;
chptr = &ch;
Notice that chptr is differently named from the other two variables, which are named ch. Why not name all three variables ch? What problem does it solve to give the pointer a different name?
Also, in the first block of code we have ...*chptr = &ch;; in the second, chptr = &ch;. What is making it acceptable to drop the asterisk in the second block?
Next, I wonder what the applications of pointers are. Do I always need a pointer (when do I need one and when do I not need one)? After submitting my answer, I feel confident--believing that I will be able to comprehend more complex code that uses pointers--enough to continue adapting the language intuitively. I'm still riddled with curiosity, though.
Take this block of code, for example:
typdef struct person
{
char *name;
int age;
}
Why declare the name as a pointer to a name variable that doesn't exist, and why declare the age variable as an int without using pointers? That wouldn't make sense, due to this block:
int main()
{
/* below, the int is a pointer */
int *p;
void *up;
return 0;
}
Or this block:
char *sp;
sp = "Hello";
printf("%s",sp);
I thought pointers pointed to an address. "Hello" isn't an address.
With the two prior blocks in mind, have a look at this final block:
int main()
{
int i,j;
int *p;
i = 5;
p = &i;
j = *p; //j = i?
&p = 7; //i = 7?
}
Shouldn't j be set to &i because *p = &i not i. And shouldn't &p = 7 set the address of p to 7, which may not be i?