BillGill said:
Ok, I assume this has been asked many times, but I can't seem to come up
with
a good Google search to find it.
I am trying to learn C++. Specifically I have Microsoft Visual C++ 2005
Express Edition. I am trying to learn it from Ivor Horton's Beginning
Visual C++ 2005.
My problem comes when we get to pointers. I just cannot seem to wrap my
mind around the complexities involved. Is there some place, either a book
or a website that will take me by the hand and lead me carefully through
the maze?
I do understand a lot about programming. I know Visual Basic, but want to
expand my abilities.
Modern computers access memory through the use of "address". An address
is a 32 or 64 bit number. Modern computer languages abstract these to
the concept of a "pointer". The C and C++ languages represent memory
addresses as pointers.
e.g.
char * x = "ABC";
x in this case is the address of the 'A' part of the sequence characters
'A', 'B', 'C', '\0'.
Pointers can "point" to any type, e.g.
int * p = new int[5];
In this case, p is a pointer to an int which is the first "int" in an
array of 5 ints.
Pointer arithmetic becomes fun, if you added a int value to an address
in the cpu, it would simply add the two integers, often not making much
sense. The C and C++ pointers will do somthing more reasonable. It
assumes that the object being pointed to is the atomic element so adding
an in to a pointer will address the next elements.
e.g.
int * p = new int[5];
(p+1) is a pointer to the second element in the int[5] array.
You can also subtract two pointers - e.g.
(p+2)-p evaluates to 2.
Pointers are not very useful unless you can access the object being
pointed to. There are a number of ways to do that.
*p - this references the object being pointed to
p[0] - this is the same as *(p+0) - which is *p
p[N] - this is the same as *(p+N)
note that 0[p] is also the same as *p ... somthing Kernigan should have
avoided IMHO...
There are a few more ways to deref a pointer.
If you have a struct - e.g.
struct A { int a; };
A * p = new A;
(*p).a - is one way of dereferencing the a element of the object pointed
to by p.
p->a does the same thing !!!
In c++ you also have "pointer to member" which can be though of as the
thing that references any element of a struct.
e.g.
struct A { int a; };
int A::* m = &A::a;
A * p = new A;
p->*m referernces p->a...
There are some very interesting properties of member pointers but that
gets pretty hairy.
Hopefully this will help you grok the book you're reading a little better.