简体   繁体   中英

Why does s[s[3]] = '1' when char *s = “123”?

char* s = "123";
std::cout << s[s[3]] << std::endl; // prints 1
std::cout << s[3] << std::endl; // prints nothing?

I tried running the following snippet and the first print statement outputs 1 while the second outputs (seemingly) nothing. What is going on when the pointer is dereferenced using the length of the char pointer array here?

It is unclear why you are using the value of the character at index 3 ( s[3] ) to index the string again. But in any case, the key point here is that you're using a char to index an array. This means that the char is used as a number, the conversion happening most likely using the ASCII character encoding.

The reason you're getting nothing printed out when you print s[3] is because s is a character array with length 4, and the last character is the null terminator. Null meaning the number 0. The null terminator identifies the end of the string. But it is not a printable character , because it is not meant to be printed. It doesn't have a gliph associated with it, so you don't get anything printed.

Of course, you can see now that s[s[3]] is nothing but s[0] , which is the character "1".

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