1,的的strcpy的用法,把一个字符串的内容拷贝给另一个字符串。
函数的原型如下
_CRTIMP char * __cdecl strcpy(char * dest,const char * src);
把SRC字符串的内容赋值给DEST,当然DEST要有足够的空间能放得下SRC拷贝过来的字符串,拷贝的过程中的src遇到'\ 0'字符串就停止了。
#include <stdio.h>
#include <string.h>
int main(void){
char dest [30];
char * src =“123456789”;
strcpy(DEST,SRC);
return 0;
}
运行结果:123456789
如果SRC的空间长度不够的话,运行就崩了。像这样。
2.memcpy是对内存的拷贝,不局限于字符串的拷贝。
_CRTIMP void * __cdecl memcpy(void * dest,const void * src,size_t n);
函数里面有三个参数,从SRC地址开始位置拷贝Ñ个字节长度到DEST的所指地址内存的起始位置,所以所每次的拷贝就把DEST指向的空间里面存放的内容覆盖掉了。
#include <stdio.h>
#include <string.h>
int main(void){
char dest [30];
char * src =“djis \ 0sejfidsjfoi”;
int i;
FILE * fp;
memcpy(dest,src,sizeof(char)* 15);
dest [15] ='\ n'; //注意要加上0结束标志
for(i = 0; 我<15; i ++){
printf(“[%c]”,dest [i]);
}
return 0;
}
虽然SRC字符串中间有一个\ 0但是拷贝的是一段内存上存放的值,最终还是会副本这一段字符串的内容到目中。
输出结果:[d] [j] [i] [s] [] [s] [e] [j] [f] [i] [d] [s] [j] [f] [o]
的memcpy不仅可以用于字符串拷贝,可以拷贝任何类型void *的,传递的参数可以指向任何类型。
可以拷贝一段数组元素
#include <stdio.h>
#include <string.h>
int main(void){
int dest [10] = {0};
int src [] = {1,2,3,4,5,6,7};
int i;
memcpy(dest,src,sizeof(int)* 6);
for(i = 0; i<10; i ++){
printf(“[%d]”,dest [i]);
}
return 0;
}
输出结果:[1] [2] [3] [4] [5] [6] [0] [0] [0] [0]
3,memset的用于格式化一段内存,将一段内存全部设为某个字符
_CRTIMP void * __cdecl memset(void * src,int ch,size_t n);
将SRC开始后面Ñ个字节内存的内容都赋值为CH所对应的ASCLL码。
#include <stdio.h>
#include <string.h>
int main(void){
char src [20];
int i;
memset(SRC, 'X',10);
for(i = 0; i<20; i ++){
printf(“[%c]”,src [i]);
}
return 0;
}
输出结果:[X] [X] [X] [X] [X] [X] [X] [X] [X] [X] [] [] [] [] [] [] [] [] [ ] []