c - Sizeof 与 Strlen

标签 c sizeof strlen

#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

是我的语法有问题还是什么?

最佳答案

sizeofstrlen() 做不同的事情。在这种情况下,您的声明

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/

相关文章:

c - 在 C 中显示字节

c++ - 什么决定了这里的对象大小?

c - 读取不一致的文件

c++ - Dllmain 可以使用 FreeLibrary 吗?

c++ - 与字符串文字不同,为什么具有单独字符的字符数组不以空终止符结尾?

c++ - C++中枚举类型数据的大小是多少?

c - static size_t strnlen(const char *s, size_t max) -- 为什么是静态返回值?

C - 如何对文本文件使用 strcmp

assembly - 如何在 Assembly 中使用 scasb 查找字符串长度

c - 如何使用 XOR 查找数组中出现次数为奇数的单个元素?