是什么的memcpy()和函数strncpy()给出了前者,后者很容易被替代的区别? [英] What is the difference between memcpy() and strncpy() given the latter can easily be a substitute for the former?

查看:927
本文介绍了是什么的memcpy()和函数strncpy()给出了前者,后者很容易被替代的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是之间的差异显著的memcpy()函数strncpy()?我问这个,因为我们可以很容易地修改函数strncpy()来,只需用铸造前两个非复制我们想要的,而不仅仅是字符的任何类型的数据 - 的char * 参数的char * 和改变第三个参数作为非char类型的大小的倍数。在下面的程序,我已经成功地使用了一个整数数组到其他的复制一部分,它的工作原理一样好的memcpy()

What is the significant difference between memcpy() and strncpy()? I ask this because we can easily alter strncpy() to copy any type of data we want, not just characters, simply by casting the first two non-char* arguments to char* and altering the third argument as a multiple of the size of that non-char type. In the following program, I have successfully used that to copy part of an integer array into other, and it works as good as memcpy().

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


    int main ()
    {
    int arr[2]={20,30},brr[2]={33,44};
    //memcpy(arr,brr,sizeof(int)*1);
    strncpy((char*)arr,(char*)brr,sizeof(int)*1);
    printf("%d,%d",arr[0],arr[1]);

    }

同样,我们可以把它用于浮动或其它数据类型的工作。那么,什么是从的显著差异的memcpy()

Similarly, we can make it work for float or other data-type. So what's the significant difference from memcpy()?

PS:同时,我不知道为什么的memcpy()文件string.h 头文件,因为几乎所有的库函数有相关的字符串,而的memcpy()在本质上是更通用。什么理由?

PS: Also, I wonder why memcpy() is in string.h header file, given nearly all of the library functions there are related to character strings, while memcpy() is more generic in nature. Any reason?

推荐答案

简单的区别是,的memcpy()可以复制嵌入空字符数据(即字符串结束在C风格的字符串),而函数strncpy()只能将字符串复制到最大给定的字符数或第一个空字符的位置(和垫的休息与0的字符串)。

The simple difference is that memcpy() can copy data with embedded null characters (aka the string terminator in C-style strings) whereas strncpy() will only copy the string to the maximum of either the number of characters given or the position of the first null character (and pad the rest of the strings with 0s).

在换句话说,它们有两个很不同的用例。

In other words, they do have two very different use cases.

这篇关于是什么的memcpy()和函数strncpy()给出了前者,后者很容易被替代的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆