Lets say I have a prepend function:
//for example xMessage = "apple";
//for example yMessage = "juice";
//answer should be newMessage = "applejuice"
char* concat(char *xMessage, int xSize, char* yMessage, int ySize){
char newMessage[xSize+ySize];
for(....){
//copyxMessage
}
for(....){
//copyYMessage
}
return (char *) newMessage;
}
I know I can use strings, but I can’t do it for this issue.
>Solution :
Note: I absolutely do not agree with doing this, but since you know you can use a std::string but would like to do it with raw pointers, here’s one way:
- Allocate a buffer large enough to hold
xSize + ySizecharacters + 1 extra for the terminating\0. You do this withnew[]. std::memcpythe input strings into the allocated buffer.- Don’t forget to
delete[]the buffer after use.
#include <cstring>
char* concat(const char *xMessage, int xSize, const char* yMessage, int ySize) {
char* newMessage = new char[xSize + ySize + 1];
std::memcpy(newMessage, xMessage, xSize);
std::memcpy(newMessage + xSize, yMessage, ySize);
newMessage[xSize + ySize] = '\0';
return newMessage;
}