1
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) 中包含的字符数?

4

2 回答 2

4

这是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++ 字符串,因为它们可以为您节省很多麻烦)。

于 2013-06-09T11:46:59.177 回答
1

该函数sizeof()以字节为单位返回数据类型的大小
例如因为您定义:

char* string = "hello there";

那么stringis的类型char *和大多数指针的大小是 4 字节(这个函数返回 4)但是*stringis的类型char和每个字符的大小是 1 字节(这个函数返回 1)
解决方案:
备选方案 1:strlen()在库'字符串中使用函数。H'

备选方案 2:(从头开始)

int length = 0;
int index = 0;
while ( string[index] != '\0')
{
length++;
index++;
}
于 2013-06-09T11:56:29.567 回答