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 :)

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.

>>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.

This article has been dead for over six months. Start a new discussion instead.