char*--strcpy--strcat实现的感悟

来源:互联网 发布:杨幂用什么软件直播 编辑:程序博客网 时间:2024/06/10 04:08
#include <iostream>
#include <stdio.h>
#include <stdlib.h>


using namespace std;
char* gc(char* a,char* b)
{
char* num=(char*)malloc(strlen(a)+strlen(b));


char* p = num;//记录初始的首地址
while (*a != '\0')
{
*num++=*a++;//把a的字符串放到num
}
//while (*b != '\0')
//{
// *a++= *b++;//这里记得要带*号
//}
//while ((*a++ = *b++) != '\0');
while (*b != '\0')
{
*num++ = *b++;
}
*num = *b;//因为字符串的末尾都是\0,没有字符串补上\0,就会导致出现乱码的情况。
return p;
}
int main()
{
//char str[13];
char* i = "123456";
char* g = "ndjdj";
char* tryy ;
tryy = gc(i,g);
cout << tryy << endl;

return 0;

}


char*创造出来的指针,事实上暂时是个野指针,我当初认为,char* i = "123456";就是把char* i = "123456"赋值给i其实是错误的,因为,char* i = "123456"其实是建立在静态存储区上的一些数据,i仅仅是指向该字符串的首地址而已,当你打印i的时候,新手的我就会误以为这些数据被赋予了i。知道了这个,我们就可以手动的写一个,char* i = "123456";
char* g = "ndjdj";

把上面2个字符串连起来的函数了,方法就是创建一个char*的变量,给他赋予一定的空间,然后一个个赋值过去,就可以实现这个功能了。其实指针也没有我想的那么简单哈。


然后还可以另一种方法实现:就是再增加一个参数,然后在main里面增添一个char  num[100],这样,就不用再gc()里面为num   malloc了。指针指向了num数组的首地址.

char* gc(char* a,char* b,char* num)
{
//char* num=(char*)malloc(strlen(a)+strlen(b));
cout <<"num的空间大小为"<< strlen(num) << endl;
char* p = num;//记录初始的首地址
while (*a != '\0')
{
*num++=*a++;//把a的字符串放到num
}
//while (*b != '\0')
//{
// *a++= *b++;//这里记得要带*号
//}
//while ((*a++ = *b++) != '\0');
while (*b != '\0')
{
*num++ = *b++;
}
*num = *b;//因为字符串的末尾都是\0,没有字符串补上\0,就会导致出现乱码的情况。
return p;
}
int main()
{
string a = "123456";
char num[100];
char str[13]= "123456";
char* i = "123456";
char* g = "ndjdj";
char* tryy ;
tryy = gc(i,g,num);
cout << tryy << endl;
cout << "sizeof是算上\ 0的" << sizeof(a) << endl;

return 0;
}

原创粉丝点击