Combine Character Arrays

I have two arrays defined as follows

1
2
char* str1;
char* str2;

what I want to do is to combine these two into one for example
str3
ok got it almost working but it returns the following in my program

h7öÄDLL Received Calling DLL

everything is correct but the very beginning "h7öÄ"

what could be causing this. The following is the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	char* XPortMsg(char* inmsg)
	{
		char* mHeader = "DLL Received: ";
		// retrieve incoming string and assign to variable
		char* msgHeader = new char[strlen(inmsg)+1];
		memcpy(msgHeader,inmsg,strlen(inmsg)+1);
		
		char* retVal = new char[strlen(mHeader)+strlen(msgHeader)+1];
		
		// Assemble the string
		strcat(retVal,mHeader);
		strcat(retVal,msgHeader);

		return retVal;
	}
After that statement

char* retVal = new char[strlen(mHeader)+strlen(msgHeader)+1];

write

*retVal = '\0';

Also after

memcpy(msgHeader,inmsg,strlen(inmsg)+1);

write

msgHeader[strlen( inmsg )] = '\0';
Last edited on
1
2
3
		// Assemble the string
		strcpy(retVal,mHeader);
		strcat(retVal,msgHeader);


That did it vlad thanks so much. I've included the complete code in case anyone else searches for this and needs it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	char* XPortMsg(char* inmsg)
	{
		char* mHeader = "DLL Received: ";
		// retrieve incoming string and assign to variable
		char* msgHeader = new char[strlen(inmsg)+1];
		memcpy(msgHeader,inmsg,strlen(inmsg)+1);
		msgHeader[strlen( inmsg )] = '\0';

		char* retVal = new char[strlen(mHeader)+strlen(msgHeader)+1];
		*retVal = '\0';
		
		// Assemble the string
		strcat(retVal,mHeader);
		strcat(retVal,msgHeader);

		return retVal;
	}

also could you briefly explain to me what *retVal ='\0'; is doing
it looks like it is appending a '\0' but i'm confused about what the *retVal does. or a nice link to a good explanation would be even better :)
thanks again
new char ... returns an uninitialsed block of memory. A string is null terminated, but your retVal thing is uninitialised.

You can make it into a string by making it null terminated with
 
*retVal = '\0';

or by just copying the string in with strcpy instead of concatinating the string with strcat.
Topic archived. No new replies allowed.