[英]string s = “hello” vs string s[5] = {“hello”}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
prints olleh
打印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;
}
prints hello
打印hello
Please help me understand why is such difference. 请帮助我理解为什么会有这种区别。 I am newbie in c++, I am using c++ 11. Ok, I corrected to s[5]={"hello"} from s[5]="hello" . 我是c ++的新手,正在使用c ++11。好的,我已从s [5] =“ hello”纠正为s [5] = {“ hello”}。
The first is a single string. 第一个是单个字符串。 The second is an array of five strings, and initializes all five string to the same value. 第二个是五个字符串的数组,并将所有五个字符串初始化为相同的值。 However, allowing the syntax in the question is a bug (see the link in the comment by TC) and should normally give an error. 但是,允许在问题中使用语法是一个错误(请参阅TC注释中的链接),通常应该会给出错误。 The correct syntax would have the string inside braces, eg { "hello" }
. 正确的语法将字符串放在大括号内,例如{ "hello" }
。
In the second program you are only printing one string of the five anyway, the first one. 无论如何,在第二个程序中,您只打印五个字符串中的一个,即第一个。 When you dereference an array, it decays to a pointer and gives you the value that pointer points to, which is the first element in the array. 取消引用数组时,它会衰减为指针,并为您提供指针指向的值,该值是数组中的第一个元素。 *s
and s[0]
are equivalent. *s
和s[0]
是等效的。
I think that what you are looking for is this: 我认为您正在寻找的是:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
With char[6]
you have an C-style string. 使用char[6]
可以得到一个C风格的字符串。 Remember that theses strings must be terminated with '\\0'
. 请记住,这些字符串必须以'\\0'
结尾。 Therefore there is a 6th element. 因此,有一个第六要素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.