Related Content:
highlighted comments:
c/c++中sizeof()、strlen()、length()、size()详解和区别
==> string::length() == string::size(); the former is for c_str compatiability, latter is for STL
C语言 char *、char []、const char *、string的区别与相互转换
test code:
#include <iostream>
#include <string>
#include <typeinfo>using namespace std;
#define DEBUG1 1
#define DEBUG0 0int main(){
//test string
char cs[] = "test string";
char* csap = cs; //usage is the same as the dynamic array but the sizeof() report 8 bytes//!!! but notice that char cs[] = "some string" is NOT the same as char* csp = "some string"
//cs[] is a mutable array of char, while char* csp points to a string constant ==> you can actually perform csp[i] = 'char' but the data csp points to won't actuallty be changed at all;
//char* csp = "test string"; warning
const char* csp = "test string"; //same as csap except that the string content is constant, stored in the text
string s = "test string";#if DEBUG1
cout << sizeof(cs) << ' ' << sizeof(csap) << ' ' << sizeof(csp) << ' ' << sizeof(s) << endl;
//string s has actual size 32 ==> similar to vec, with reserved capacitycout << cs << endl << csap << endl << csp << endl << s << endl;
cout << *cs << ' ' << *csap << ' ' << *csp << endl; //*s is not declaredcout << ++cs[0] << ' ' << (++csap)[0] << ' ' << (++csp)[1] << ' ' << ++s[0] << endl;
//!! ++cs is not allowed ==> char* const cs; similary ++s is not allowed either
//++csp is fine, so is ++csap ==> they are not const*cout << typeid(cs).name() << ' ' << typeid(csap).name() << ' ' << typeid(csp).name() << ' ' << typeid(s).name() << endl;
cs[2] = 'r';
*csap++ = 'a';
*++csap = 'b';
cout << cs << endl;
//csp[2] = 'r'; // error: assignment of read-only location '*(csp + 2)' ==> global constants are stored in the .text area
#endifreturn 0;
}