字符串 s = "hello" vs 字符串 s[5] = { "hello" }

string s = "hello" vs string s[5] = {"hello"}

本文关键字:字符串 hello vs      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
  string s = "hello";
  reverse(begin(s), end(s));
  cout << s << endl;
  return 0;
}

打印olleh

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
  string s[5] = {"hello"};
  reverse(begin(s), end(s));
  cout << *s << endl;
  return 0;
}

打印hello

请帮助我理解为什么会有这样的差异。我是 c++ 的新手,我使用的是 c++ 11。好的,我从 s[5]="hello" 更正为 s[5]={"hello"} .

第一个是单个字符串。第二个是五个字符串的数组,并将所有五个字符串初始化为相同的值。但是,在问题中允许语法是一个错误(请参阅T.C.评论中的链接),通常应该给出错误。正确的语法是将字符串放在大括号内,例如 { "hello" } .

在第二个程序中,您只打印五个字符串中的一个字符串,第一个。取消引用数组时,它会衰减到指针,并为您提供指针指向的值,即数组中的第一个元素。 *ss[0]是等效的。

我认为您正在寻找的是:

int main() {
  char s[] = "hello";
  reverse(s, s + (sizeof(s) - 1));
  cout << string(s) << endl;
  return 0;
}

有了char[6],你就有一个 C 样式的字符串。请记住,这些字符串必须以 '' 结尾。因此,有第 6 个元素。