【发布时间】:2012-04-13 19:07:11
【问题描述】:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char string[] = "october"; // 7 letters
strcpy(string, "september"); // 9 letters
printf("the size of %s is %d and the length is %d\n\n", string,
sizeof(string), strlen(string));
return 0;
}
输出:
$ ./a.out
the size of september is 8 and the length is 9
我的语法有什么问题吗?
【问题讨论】:
-
您正在写超出数组
string的末尾。这是未定义的行为。string只能包含 8 个字符(7 个用于“october”,1 个用于空终止符)。当您调用strcpy时,您正在向其写入 10 个字符(9 代表“九月”,1 代表空终止符),这意味着您已经超过了数组的末尾并正在覆盖相邻的内存。 -
请注意,
sizeof是在 编译 时计算的,而strlen是运行时。 -
@Naveen:请注意,在涉及 VLA 的情况下,这不一定是正确的。
-
@caf:也许我会觉得一无所知,但是.....你说的 VLA 是什么意思?非常大的数组?大声笑
-
我是说在函数
int foo(int n) { int a[n];的值sizeof a不是在编译时计算的。