<分区>
Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8
Sizeof 打印出 6 用于:
printf("%d\n", sizeof("abcde"));
但它打印出 4 用于:
char* str = "abcde";
printf("%d\n", sizeof(str));
谁能解释一下为什么?
<分区>
Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8
Sizeof 打印出 6 用于:
printf("%d\n", sizeof("abcde"));
但它打印出 4 用于:
char* str = "abcde";
printf("%d\n", sizeof(str));
谁能解释一下为什么?
最佳答案
字符串文字"abcde"
是一个字符数组。它有 6 个字节长,包括空终止符。
char*
类型的变量是指向字符的指针。它的大小是一个指针的大小,在 32 位系统上是 4 个字节。 sizeof
是编译时操作†,因此它只查看变量的静态类型,在本例中为 char*
。它不知道指向什么。
† 可变长度数组除外,这是 C99 语言标准中引入的一个特性
关于c - 为什么 sizeof 在 C 中对同一个字符串返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9644267/