When dealing with pointers, people that get confused are widely in one of two camps. I've been (am?) in both.
The array[] crowd
This is the crowd that straight up doesn't know how to translate from pointer notation to array notation (or doesn't even know that they are even related). Here are four ways to access elements of an array:
- array notation (indexing) with the
array name
- array notation (indexing) with the
pointer name
- pointer notation (the *) with the
pointer name
- pointer notation (the *) with the
array name
int vals[5] = {10, 20, 30, 40, 50};
int *ptr;
ptr = vals;
array element pointer
notation number vals notation
vals[0] 0 10 *(ptr + 0)
ptr[0] *(vals + 0)
vals[1] 1 20 *(ptr + 1)
ptr[1] *(vals + 1)
vals[2] 2 30 *(ptr + 2)
ptr[2] *(vals + 2)
vals[3] 3 40 *(ptr + 3)
ptr[3] *(vals + 3)
vals[4] 4 50 *(ptr + 4)
ptr[4] *(vals + 4)
The idea here is that accessing arrays via pointers seems pretty simple and straightforward, but a ton of very complicated and clever things can be done this way. Some of which can leave experienced C/C++ programmers befuddled, let alone inexperienced newbies.
The reference to a pointer and pointer to a pointer crowd
This is a great article that explains the difference and which I'll be citing and stealing some code from :)
As a small example, it can be very difficult to see exactly what the author wanted to do if you came across something like this:
//function prototype
void func(int*& rpInt); // I mean, seriously, int*& ??
int main()
{
int nvar=2;
int* pvar=&nvar;
func(pvar);
....
return 0;
}
Or, to a lesser extent, something like this:
//function prototype
void func(int** ppInt);
int main()
{
int nvar=2;
int* pvar=&nvar;
func(&pvar);
....
return 0;
}
So at the end of the day, what do we really solve with all this gibberish? Nothing.
Now we have seen the syntax of
ptr-to-ptr and ref-to-ptr. Are there
any advantages of one over the other?
I am afraid, no. The usage of one of
both, for some programmers are just
personal preferences. Some who use
ref-to-ptr say the syntax is "cleaner"
while some who use ptr-to-ptr, say
ptr-to-ptr syntax makes it clearer to
those reading what you are doing.
This complexity and the seeming (bold seeming) interchangeability with references ,which is often another caveat of pointers and an error of newcomers, makes understanding pointers hard. It's also important to understand, for completion's sake, that pointers to references are illegal in C and C++ for confusing reasons that take you into lvalue-rvalue semantics.
As a previous answer remarked, many times you'll just have these hotshot programmers that think they are being clever by using ******awesome_var->lol_im_so_clever() and most of us are probably guilty of writing such atrocities at times, but it's just not good code, and it's certainly not maintainable.
Well this answer turned out to be longer than I had hoped...