Sizeof 与 Strlen

2023-12-06

#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;
}

Output:

$ ./a.out
the size of september is 8 and the length is 9

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


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

char string[] = "october";

是相同的

char string[8] = "october";

所以编译器可以知道的大小string是 8。它在编译时执行此操作。

然而,strlen()计算运行时字符串中的字符数。所以,在你打电话之后strcpy(), string现在包含“九月”。strlen()计算字符数并找到其中的 9 个。请注意,您没有分配足够的空间string举办“九月”。这是未定义的行为。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Sizeof 与 Strlen 的相关文章

随机推荐