gpt4 book ai didi

c - 为什么需要将 NUL 字符附加到数组中?

转载 作者:行者123 更新时间:2023-11-30 21:14:39 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>

int main()
{
char x[] = "Happy birthday to You";
char y[25];
char z[15];

printf("The string in array x is: %s\nThe string in array y is: %s\n", x, strcpy(y, x));

strncpy(z, x, 14);

z[14] = '\0'; // Why do I need to do this?
printf("The string in array z is: %s\n", z);
return 0;
}
  1. 为什么需要将 NUL 字符附加到数组 z 中?
  2. 我还评论了该行,但输出没有改变,为什么?
  3. 如果我执行类似 z[20] = '\0'; 的操作,它就会编译并显示结果,没有任何错误。当我声明 z 数组的大小为 15 时,这不是对内存的非法访问吗?

最佳答案

C语言没有原生的字符串类型。在 C 中,字符串实际上是一维字符数组,以空字符 \0 结尾。

Why do I need to append a NUL character to the array z?

C 库函数(如 strcpy()/strncpy())对以 null 结尾的字符数组进行操作。 strncpy() 将最多 count 个字符从源复制到目标。如果找到终止空字符,则将其复制到目标并返回。如果在复制整个源数组之前达到 count,则生成的字符数组不是以 null 终止的,您需要在目标末尾显式添加 null 终止字符。

Also I commented that line and the output didn't change, Why?

我唯一能说的是你很幸运。也许目标的最后一个字符(即 z[14])可能具有所有位 0。但这种情况可能不会在每次运行程序时发生。确保在使用 strncpy() 时显式添加空终止字符,或使用其他一些自动为您执行此操作的 C 库函数,例如 snprintf()

And if I do something like z[20] = '\0'; it's compiling and showing me result without any errors. Isn't that illegal access to memory as I declared my z array to be the size of 15?

数组 z 的大小为 15 并且您正在访问 z[20] 即访问数组 z超出其尺寸。在 C 中,越界访问数组是未定义的行为。未定义的行为包括程序可能执行不正确(崩溃或默默地生成不正确的结果),或者它可能偶然完全按照程序员的意图执行。

关于c - 为什么需要将 NUL 字符附加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51683369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com