<分区>
char* string = "hello there";
cout << sizeof( string ); // prints 4, which is the size of pointer
cout << sizeof( *string ); // prints 1, which is the size of char
如何获取字符串 (11) 中包含的字符数?
<分区>
char* string = "hello there";
cout << sizeof( string ); // prints 4, which is the size of pointer
cout << sizeof( *string ); // prints 1, which is the size of char
如何获取字符串 (11) 中包含的字符数?
最佳答案
您需要的是 strlen
,而不是 sizeof
。第一个计算直到终止 NUL 的字符数,而第二个为您提供类型的大小,在本例中,它是一个指针,而不是底层字符数组。
最后一点,我的意思是:
char *x = "hello there";
char y[] = "hello there";
std::cout << sizeof(x) << ' ' << sizeof(y) << '\n';
很可能会输出如下内容:
4 12
在具有 32 位指针(和 8 位 char
)的系统上。在这种情况下,4
是指针的大小,12
是数组中的字节数(包括末尾的 NUL)。
无论如何,这是没有实际意义的,因为 strlen()
是获取 C 字符串长度的正确方法(是的,即使在 C++ 中,尽管您可能想考虑使用 C++ 字符串因为它们可以为您省去很多麻烦)。
关于c++ - 努力获取 char* 中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17009238/