为什么打印c样式字符串的“索引n的地址”会导致子字符串的输出

我是C ++的新手,在使用指向char数组(C样式字符串)的指针时,我对它与ostream对象的行为感到困惑。

const char* items {"sox"};
cout << items << endl;
cout << items[0] << endl;
cout << *items << endl;
cout << &items << endl;
cout << &items[1] << endl;

运行此命令将导致:

sox
s
s
0x7fff2e832870
ox

In contrary to pointer of other data types, printing the variable doesn't output the address, but the string as a whole. By what I understand, this is due to the << operator being overloaded for char arrays to treat them as strings.

What I don't understand is, that cout << &items[1] prints the string from index 1 onward (ox), instead of the address of the char at index 1. Is this also due to << operator being overloaded or what is the reason for this behavior?

评论
  • 时间在怂恿
    时间在怂恿 回复

    items[1] is the second character of the array and its address, i.e. &items[1], is a pointer to the second character (with index 1) as well. So, with the same rule that you have mentioned for operator <<, the second character of the string till the end is printed.

  • 北极想你
    北极想你 回复

    The type of &items[1] is char *. Therefore the const char * overload of operator << is used, which prints the string from index 1 onwards.

    OTOH, the type of &items is std::string *, for which no specific overload exists, so the address of the string variable itself is printed.