gpt4 book ai didi

c - strncpy 和 memcpy 之间的区别?

转载 作者:太空狗 更新时间:2023-10-29 16:29:13 32 4
gpt4 key购买 nike

如何在 s 中访问 s[7]

我没有观察到 strncpymemcpy 之间有任何区别。如果我想打印输出 s 以及 s[7](如 qwertyA),我必须在以下代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
char s[10] = "qwerty", str[10], str1[10];
s[7] = 'A';
printf("%s\n", s);
strncpy(str, s, 8);
printf("%s\n", str);
memcpy(str1, s, 8);
printf("%s\n", str1);
return 0;
}

输出:

qwerty
qwerty
qwerty

最佳答案

其他人已经指出了您的空终止问题。在了解 memcpystrncpy 之间的区别之前,您需要先了解空终止。

主要区别在于 memcpy 将复制您要求的所有 N 个字符,而 strncpy 将复制直到包含第一个空终止符或 N 个字符, 以较少者为准

如果复制少于 N 个字符,它将用空字符填充其余部分。

关于c - strncpy 和 memcpy 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4593907/

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