#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
是我的语法有问题还是什么?
最佳答案
sizeof
和 strlen()
做不同的事情。在这种情况下,您的声明
char string[] = "october";
与
相同char string[8] = "october";
所以编译器可以知道 string
的大小是 8。它在编译时执行此操作。
但是,strlen()
在运行时计算字符串中的字符数。因此,在您调用 strcpy()
之后,string
现在包含“september”。 strlen()
对字符进行计数并找到其中的 9 个。请注意,您没有为 string
分配足够的空间来容纳“september”。这是未定义的行为。
关于c - Sizeof 与 Strlen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9937181/