简体   繁体   中英

Pointer and char array confusion

#include <iostream>
using namespace std;
int main()
{
 char str[] {"TESTING"};
 char *p {str};
 cout << (p++, *++p);
 cout << *p++;
 cout << p;
 return 0;
}

It returns "SSTING"

I know maybe this post isn't exactly for stackoverflow but I can't figure out what it does, and couldn't find any documentation about it

 cout << (p++, *++p); 

First time I saw round brackets with comma in cout... what's their function?

and shouldn't this line alone say "TESTING" but it seems to say only TING

cout << p;

Thank you!

Let's go line by line:

char str[] {"TESTING"};

This line defines a variable named str of type array of 8 chars , and initializes it with the characters TESTING plus a NUL char to mark the end.

char *p {str};

This one defines a variable named p of type pointer to char and initializes it to the address of the first char of the array str (the first T ). This happens because the array automatically decays into a pointer in most uses.

cout << (p++, *++p);

This line does several things. The , operator first evaluates the left-hand operator p++ , that increments the pointer, now points to the E ; then it evaluates the right-hand operator *++p , but that is a pre-increment operator so it increments the pointer again (it points to S ). Finally the * operator accesses to the memory pointed to by p , the result is a S . And that character is printed into STDOUT.

cout << *p++;

This one is easy. The * operator accesses the char pointed to by p (the S again) and prints it in STDOUT. Then it increments the pointer, because it is a post-increment operator. Now it points to the second T .

cout << p;

And at least, this line prints the string pointed to by p until it finds a NUL character. Since p is pointing to the second T of your array it will print TING .

Putting all those outputs together you get SSTING .

Not exactly an answer, but a breakdown of what was the code doing,

#include <iostream>

using namespace std;

int main()
{
    char str[]{"TESTING"};
    char *p{str}; // p points to: 'T'
    p++;          // p points to: 'E'
    ++p;          // p points to: 'S'
    cout << *p;   // output a single char: 'S'
    cout << *p;   // ouptut a single char: 'S'
    p++;          // p points to: 'T'
    cout << p;    // output a (char *) type pointer, AKA a C-string, "TING";

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM