简体   繁体   中英

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

#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

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" .

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. The correct syntax would have the string inside braces, eg { "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.

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. Remember that theses strings must be terminated with '\\0' . Therefore there is a 6th element.

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