当前位置:首页>正文

这个mymemcpy()内存拷贝函数干嘛用: C语言串拷贝(strcpy)和内存拷贝(memcpy)函数有什么不同?

2023-07-07 00:54:47 互联网 未知

这个mymemcpy()内存拷贝函数干嘛用:


内存拷贝 就是复制一段一模一样的数据

传参进去---就是将要复制的首地址和目标地址告诉函数

函数里定义的指针分别指向各个需要的地址

然后操作指针 将待复制的内存内容拷贝到目标地址

拷贝完之后将目标地址返回 这个地址上记录这一串复制后的内存

原里上和拷贝字符串函数(strcpy)类似 只是memcpy用指针操作,拷贝的是内存内容,也就是说不限制内存里面是什么内容 都能拷贝

C语言串拷贝(strcpy)和内存拷贝(memcpy)函数有什么不同?

strcpy()函数只能拷贝字符串。strcpy()函数将源字符串的每个字节拷贝到目录字符串中,当遇到字符串末尾的null字符()时,它会删去该字符,并结束拷贝。
memcpy()函数可以拷贝任意类型的数据。因为并不是所有的数据都以null字符结束,所以你要为memcpy()函数指定要拷贝的字节数。
在拷贝字符串时,通常都使用strcpy()函数;在拷贝其它数据(例如结构)时,通常都使用memcpy()函数。以下是一个使用strcpy()函数和memcpy()函数的例子:
#include
#include
typedef struct cust-str {int id char last_name [20]
char first_name[l5]} CUSTRECvoid main (void)
void main (void){char * src_string = "This is the source string"
char dest_string[50]
CUSTREC src_cust
CUSTREC dest_cust
printf("Hello! Im going to copy src_string into dest_string!
")
/ * Copy src_ string into dest-string. Notice that the destination
string is the first argument. Notice also that the strcpy()
function returns a pointer to the destination string. * /
printf("Done! dest_string is: %s
" ,
strcpy(dest_string, src_string))
printf("Encore! Lets copy one CUSTREC to another.
")
prinft("Ill copy src_cust into dest_cust.
")
/ * First, intialize the src_cust data members. * /
src_cust. id = 1
strcpy(src_cust. last_name, "Strahan")
strcpy(src_cust. first_name, "Troy")
/ * Now, Use the memcpy() function to copy the src-cust structure to
the dest_cust structure. Notice that, just as with strcpy(), the
destination comes first. * /
memcpy(&dest_cust, &src_cust, sizeof(CUSTREC))