在C++中如何比较字符数组与字符串的大小?

Yel*_*aYR 3 c++ arrays string size character

我有以下声明

char c[] = "Hello";
string c2 = "Hello";
Run Code Online (Sandbox Code Playgroud)

我想比较a)需要多少字节的内存和b)字符长度.我知道字符数组在字符串的末尾添加一个空终止符,而不是字符串数据类型.

运用

cout << "The sizeof of c: " << sizeof(c);
cout << "The sizeof of c2: " << sizeof(c2);
Run Code Online (Sandbox Code Playgroud)

返回6和4,我不知道为什么4而不是5?长度函数如何在这里比较...

当我使用以下代码时

cout << "The sizeof of c: " << sizeof(c);
cout <<"The sizeof of c2: " << c2.length();
Run Code Online (Sandbox Code Playgroud)

我得到6和5 ......但它是否以相同的方式比较长度?谢谢.

Vla*_*cow 8

a)有多少记忆需要和

您正确使用了sizeof运算符来确定字符数组占用的字节数.

它是

sizeof( c )
Run Code Online (Sandbox Code Playgroud)

至于类型的对象,std::string它占用两个范围的内存.第一个用于分配对象本身,第二个用于分配对象保存的字符串.

所以

sizeof( c2 )
Run Code Online (Sandbox Code Playgroud)

将给出对象占用的内存大小.

c2.capacity()
Run Code Online (Sandbox Code Playgroud)

将为您提供分配用于存储字符串的对象的大小,以及将来可能填充的一些其他字符.

当我使用下面的代码cout <<"c的sizeof:"<< sizeof(c); cout <<"c2的sizeof:"<< c2.length();

我得到6和5

如果你想比较字符串本身没有字符数组有的终止零,那么你应该写

cout << "The length of c: " << std::strlen(c);
cout <<"The length of c2: " << c2.length();
Run Code Online (Sandbox Code Playgroud)

你会得到结果5和5.

您可以使用std :: string类型的对象进行以下实验.

std::string s;

std::cout << sizeof( s ) << '\t' << s.capacity() << '\t' << s.length() << std::endl;

std::string s1( 1, 'A' );

std::cout << sizeof( s1 ) << '\t' << s1.capacity() << '\t' << s1.length() << std::endl;

std::string s3( 2, 'A' );

std::cout << sizeof( s2 ) << '\t' << s2.capacity() << '\t' << s2.length() << std::endl;

std::string s3( 16, 'A' );

std::cout << sizeof( s3 ) << '\t' << s3.capacity() << '\t' << s3.length() << std::endl;
Run Code Online (Sandbox Code Playgroud)