天天看点

strcpy和strcat易忽略点

首先来看一段C程序:

1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 
 5 void GetMem(char*& pstr){//注意必须要用指针的指针或者指针的引用。如果传本身,返回的已经是空悬指针了
 6     pstr=(char*)malloc(20);
 7 }
 8 
 9 int main(){
10     char* str;
11     GetMem(str);
12 
13     strcpy(str,"Hello");
14     strcat(str+3,"World");//这里加的数字只要不超过Hello的长度都是一样的效果,最终都会寻找到末尾的0,然后连接
15     printf("%s",str);//HelloWorld
16     return 0;
17 }      

再看一段:

1 #include<stdio.h>
2 #include<string.h>
3 main()
4 {
5     char *p1="abc",str[50]="xyz";
6     strcpy(str+2,p1);
7     printf("%s\n",str);//xyabc,注意是从第2个位置开始覆盖的
8 }      

特别要注意这两个函数的异同。

『注:本文来自博客园“小溪的博客”,若非声明均为原创内容,请勿用于商业用途,转载请注明出处http://www.cnblogs.com/xiaoxi666/』