Hi all,
I have defined a function cat which takes in 2 cstring arguments and returns out a pointer to a new cstring which cocatenates the 2 strings

I am having 2 problems with it.

the cout statement doesnt work and secondly i get a runtime error while i delete.

I am using the G++ Compiler on Ubuntu Linux.

#include <iostream>

char* cat(const char *arg1,const char *arg2);
extern int strlen(const char *arg1);

int main()
{
char string1[]="sky";
char string2[]="Dip";
char *cated=cat(string1,string2);
std::cout<<cated;
delete [] cated;
}

char* cat(const char *arg1,const char *arg2)
{
	int a=0;
	a=(strlen(arg1)+strlen(arg2));
	char *p=new char[a+1];
	while(*arg1!=0)
	{
	*p=*arg1;
	p++;
	arg1++;
	}
	while(*arg2!=0)
	{
	*p=*arg2;
	p++;
	arg2++;
	}
	*p=0;
	return p;
}

The function strlen is another function that i wrote and which returns an int.
That seems to work fine.

line 23: oops! that just lost the location of the memory that was allocated on line 13. You need to use a different pointer for incrementing and leave the original pointer unchanged.

Ok this works

#include <iostream>

char* cat(const char *arg1,const char *arg2);
extern int strlen(const char *arg1);

int main()
{
char string1[]="sky";
char string2[]="Dip";
char *cated=cat(string1,string2);
std::cout<<cated;
delete [] cated;
}

char* cat(const char *arg1,const char *arg2)
{
	int a=0;
	a=(strlen(arg1)+strlen(arg2));
	char *q=new char[a+1];
	char *p=q;
	while(*arg1!=0)
	{
	*p=*arg1;
	p++;
	arg1++;
	}
	while(*arg2!=0)
	{
	*p=*arg2;
	p++;
	arg2++;
	}
	*p=0;
	return q;
}

I did this with the code and this works well.
Are there any other improvements in the code that can be done?

you could write a copy function to avoid the duplicate code you have

char* copy(char* to, char* from)
{
   while(*from)
     *to++ = *from++;
   *to = 0;
   return to;
}
char* cat(const char *arg1,const char *arg2)
{
    char *p = new char[strlen(arg1)+strlen(arg2)+1];
    copy( copy(p, arg1), arg2);
    return p;
}
Comments
Thanks-- That Really Helped.
This question has already been answered. Start a new discussion instead.