Changing a char array without even calling the array?

83 Views Asked by At

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 &this 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

https://youtu.be/g9oMn4mEx14

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 :)

3

There are 3 best solutions below

0
On

Draw it on paper (still the best method to both understand and write code with pointers).
Here is an ASCII version:

The beginning:

+---+---+---+---+---+---+
| h | e | l | l | o | 0 |
+---+---+---+---+---+---+
  ^               ^
  |               |
 pStart         pEnd

The loop:

save = *pStart;

+---+---+---+---+---+---+
| h | e | l | l | o | 0 |       save: h
+---+---+---+---+---+---+
  ^               ^
  |               |
 pStart         pEnd

Then:

*pStart = *pEnd;

+---+---+---+---+---+---+
| o | e | l | l | o | 0 |       save: h
+---+---+---+---+---+---+
  ^               ^
  |               |
 pStart         pEnd

Then:

 *pEnd = save;

+---+---+---+---+---+---+
| o | e | l | l | h | 0 |       save: h
+---+---+---+---+---+---+
  ^               ^
  |               |
 pStart         pEnd

And then:

pStart++;
pEnd--;

+---+---+---+---+---+---+
| o | e | l | l | h | 0 |       save: h
+---+---+---+---+---+---+
      ^       ^
      |       |
    pStart   pEnd

and you can repeat the loop yourself.
(It's much faster and easier on paper than with a computer and a keyboard.)

1
On

how can it change text without us even assigning anything to that char array anywhere? This boggles my mind.

Because the char array acts like a pointer - it's just an address to where the characters are stored. You want to be changing the characters themselves. The location in memory where the array is remains constant here.

0
On

To simplify this to pseudocode, we are essentially swapping the characters at the start and end pointers using a temp variable save.

In the code snippet you just posted, this occurs in 3 steps:

  • store start to save
  • store end to start
  • store save to end