I have studied c++ for about 2 weeks on cave of programming (while working full time :( ) and I just got an understanding for pointers. Point *pThis
to &thi
s to get the value out of this address and so on. Anyway, I just got to a video that flipped everything I knew.
I had to copy this to paper first because I am not at home I hope it is correct!
char text[] = "hello";
int nChars = sizeof(text) - 1;
char *pStart = text;
char *pEnd = text + nChars - 1;
while(pStart < pEnd)
{
char save = *pStart;
*pStart = *pEnd;
*pEnd = save;
pStart++;
pEnd--;
}
cout >> text >> endl;
I hope I wrote it correct from this video with my phone
I do understand that we are creating two pointers that points to the start and end of text and then switching them and so on. What I don't understand is how can it change text without us even assigning anything to that char array anywhere? This boggles my mind.
I hope someone can help me get this :)
Draw it on paper (still the best method to both understand and write code with pointers).
Here is an ASCII version:
The beginning:
The loop:
Then:
Then:
And then:
and you can repeat the loop yourself.
(It's much faster and easier on paper than with a computer and a keyboard.)