can someone please explain whats wrong with the below code segment? My intention is to assign characters in pointer "p" to pointer "a" one by one until the end. but this throws run time exception. I want to do assign character by chater without assigneing the entire pointer as a whole. Is there any other inbulid function to do character concatenation?

char *p = "asd";
 char * a;

  
    for (int i = 0; *p != '\0' ; ++i)
   {
     // std::cout << *p++;		
	strcat(a,p);
	p++;
  }

you have to allocate memory for pointer a. The way you have it written pointer a just points to some random memory location that your program probably does not own.

char *p = "asd";
 char * a = new char[strlen(p)+1];

The second reason your program doesn't work is because you are using strcat() incorrectly. You don't need the loop if you use that function.

char *p = "asd";
 char * a = new char[strlen(p)+1];
a[0] = '\0'; // initialize to null string
strcat(a,p);

Thankx Anc. Dra. for ur help. but the solution doesnt suits for my need. becoze i m using that character concatenation program segment in another one. basically i need to assign extracted characters into another char pointer.
e.g

//005 is the length of the trailng string, 002 is the length of the trailing string & etc. so I want to extract data comes after integers and assign them to char pointers.

char *p = "005first002eg";
  char *data = p;

  while (*data != '\0') {
        char temp[4];
        int length;
       
    sscanf(data, "%3[0123456789]", temp);
    length = std::strtol(temp, 0, 10);
    char * first= new char[length + 1];
       first[0] = '\0';

    data += 3;

    for (int i = 0; *data != '\0' && i < length; ++i)
	{
      //std::cout << *data++;
		strcat(first,data);
		data++;
	}
    std::cout << '\n';
  }
for (int i = 0; *data != '\0' && i < length; ++i)
{
strcat(first,data);
data++;
}
std::cout << '\n';
}

You can not use strcat() that way because it copies the entire source string to the destination buffer, not just a single character. If you want to copy just a single character than just use simple assignment

char* ptr = first;
for (int i = 0; *data != '\0' && i < length; ++i)
{
      *ptr++ = *data++;
}
*ptr = 0; // null terminate the string
std::cout << '\n';
}
This article has been dead for over six months. Start a new discussion instead.