Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you return a char * two char pointer? Local variable is being returned error c++

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 + ySize characters + 1 extra for the terminating \0. You do this with new[].
  • std::memcpy the 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;
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading