c - strncpy 和 memcpy 之间的区别?

标签 c memcpy strncpy

如何在 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/

相关文章:

c++ - strncpy_s - 缓冲区太小断言

c - C 中的 strncpy 和 strcat 垃圾字符

C & Libevent : add binary data to output buffer

c - 了解嵌入式 C 中命令 *__SIMD32(pIn)++ 的执行

c++ - extern "C",它有什么用?

将 void * 转换为数组

c++ - 关于使用 memcpy 将表达式值复制到指针的查询

c++ - 在内存中设置的二维数组是否与模拟二维数组的一维数组连续相似?

c - 如何让 FFTW 工作

从 C 中的 extern char environ 复制字符串