如何在 s
中访问 s[7]
?
我没有观察到 strncpy
和 memcpy
之间有任何区别。如果我想打印输出 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
最佳答案
其他人已经指出了您的空终止问题。在了解 memcpy
和 strncpy
之间的区别之前,您需要先了解空终止。
主要区别在于 memcpy
将复制您要求的所有 N 个字符,而 strncpy
将复制直到包含第一个空终止符或 N 个字符, 以较少者为准。
如果复制少于 N 个字符,它将用空字符填充其余部分。
关于c - strncpy 和 memcpy 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4593907/