我自写的一个strcat函数,但是运行中报错,请指出。

发布时间:2024-05-28 13:14 发布:上海旅游网

问题描述:

#include <iostream>
using namespace std;

char * strcat(char *strDestination,const char *strSource)
{
int nCount = strlen(strDestination);

char* pEnd = &strDestination[nCount - 1];

int nSourceCount = strlen(strSource);

for(int i = 0;i < nSourceCount;i++)
{
*pEnd = *strSource;
pEnd++;
strSource++;
}

pEnd++;
*pEnd = '\0';

return strDestination;
}

void main()
{
char* pDest = "abcd";
char* pSource = "efgh";

char* pNew = strcat(pDest,pSource);

cout<<pNew<<endl;

getchar();
}

在*pEnd = *strSource;就报错了,是什么原因?
前提是不能调用其他API

问题解答:

问题在于你的目的串是个字符数组,其长度是确定的,你将源串的字符一一复制到目的串后面,其占用的内存空间就不属于目的串了,也就是已经越界了,将会覆盖掉未知的内容,这些内容可能是有用的,也可能是无用的,C++是不允许这样做的。
正确的做法应该是,先用new操作符申请一块内存空间,要足够放下这两个字符串,然后将两个字符串依次复制到这块空间中,最后再把目的串指针strDestination指向这块空间就可以了。

你的想法太复杂了!strcat只要调用strcpy就可以很简答的完成了!

strcpy(strDes+strlen(strDes), strSrc);

函数名: strcat
功 能: 字符串拼接函数
用 法: char *strcat(char *destin, char *source);
程序例:

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

int main(void)
{
char destination[25];
char *blank = " ", *c = "C++", *Borland = "Borland";

strcpy(destination, Borland);
strcat(destination, blank);
strcat(destination, c);

printf("%s\n", destination);
return 0;
}

热点新闻