#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个字符("october"有7个字符,再加上一个空字符作为字符串结束符)。当你调用strcpy
函数时,你将会向其写入10个字符("september"有9个字符,再加上一个空字符作为字符串结束符),这意味着你超出了数组的结尾,正在覆盖相邻的内存。 - Marlonsizeof
是在编译时计算的,而strlen
是在运行时计算的。 - Naveenint foo(int n) { int a[n];
中,sizeof a
的值不是在编译时计算的。 - caf