I have been trying to concatenate two strings declared in the form of pointers i.e.

char* chars;

But the program crashes...
Here is the code:

char *chars1="ankit";
  char *chars2="sameer";
  char *temp;
  int i;
  for(i=0;i<len;i++)
  {
    temp[i] = chars1[i];
  }
  for(int j=0;j<len2;j++)
  {
    temp[i] = chars2[j];
    i++;
  }

help me out :)

temp[i] = chars1[i];

I dont think you can do that with allocating memory by using the new keyword.

you have to allocate space to temp before doing that. You need length of chars1 + length of chars2 + 1 number of bytes temp = new char[strlen(chars1) + strlen(chars2) + 1];

I dont think you can do that with allocating memory by using the new keyword.

Oops sorry I meant without instead of with.

>>All generalizations are wrong. Even this one.
I was only wrong once in my life -- that when when I thought I was wrong, but I was wrong.

Being wrong about something is the best way to learn :)

>>All generalizations are wrong. Even this one.
I was only wrong once in my life -- that when when I thought I was wrong, but I was wrong.

:D

Thanks. Its all working fine now.
One little query though, when I have to terminate the string how do i do it?
like this :

temp[i]='/0';

or

temp[i]=NULL;

When i do it by the first method, it doesn't really work and gives a warning "multi-character character constant". And in the second method, it gives a warning "conversion to non-pointer type", though it works.

temp[i]=0; or temp[i]='\0';

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.