为什么用C的sizeof不会返回相同的字符串的值不同? [英] Why does sizeof return different values for same string in C?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/4366600/sizeof-doesnt-return-the-true-size-of-variable-in-c\">Sizeof用C 结果不返回变量的真实大小
C - &GT; sizeof的字符串始终是8
Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8
sizeof的打印出6:
Sizeof prints out 6 for:
printf("%d\n", sizeof("abcde"));
但它打印出4:
char* str = "abcde";
printf("%d\n", sizeof(str));
有人能解释为什么吗?
Can someone explain why?
推荐答案
该字符串ABCDE
是一个字符的阵列的。这是6个字节长,包括空终止。
The string literal "abcde"
is a character array. It is 6 bytes long, including the null terminator.
键入的char *
的变量是的指针的一个字符。它的大小是一个指针,它在32位系统上是4个字节的大小。 的sizeof
是一个编译时的操作†,所以它只查看变量的静态类型,在这种情况下是字符*
。它已经不知道什么东西被指出。
A variable of type char*
is a pointer to a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes. sizeof
is a compile time operation†, so it only looks at the variable's static type, which in this case is char*
. It has no idea what's being pointed to.
†除变长数组的情况下,在C99语言标准引入的功能
† Except in the case of variable-length arrays, a feature introduced in the C99 language standard
这篇关于为什么用C的sizeof不会返回相同的字符串的值不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!