错误的字符串长度

kyl*_*e k 0 c string sizeof string-length

我试图得到一个字符串的长度,但我得到错误的值,它说它只有4个字符长.为什么是这样?我使用sizeof()得当吗?

#include <stdio.h>

int main(void)
{
    char *s;
    int len;

    s = "hello world";
    len = sizeof(s);
    printf("%d\n", len);
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

sizeof操作将返回指针的大小.如果需要字符串的长度,请使用该strlen函数.

即使你有一个数组(例如char s[] = "hello world"),sizeof运算符也会返回错误的值,因为它将返回包含字符串终结符字符的数组的长度.

哦,作为旁注,如果你想要一个字符串指针指向文字字符串,你应该声明它const char *,因为字符串文字是常量,不能修改.