c++arraysfunctionpointerscout

The function collects the array and returns it. After ciout memory is still occupied by this array, right?


I have the following function:

void setFore(const short arg) {
    char ansicode[12] = "\e[38;5;";
    char code[4];
    snprintf(code, 4, "%d", arg);
    strcat(ansicode, code);
    strcat(ansicode, "m");
    std::cout << ansicode;
}

Using it looks like:

std::cout << "Some text";
setFore(50);
std::cout << "Some text\n";

After execution, array ansicode is deleted automatically. I want to make the function like this:

char* setFore(const short arg) {
    char ansicode[12] = "\e[38;5;";
    char code[4];
    snprintf(code, 4, "%d", arg);
    strcat(ansicode, code);
    strcat(ansicode, "m");
    return &ansicode;
}

And use it as std::cout << "Some text" << setFore(50) << "Some text\n";. But one question remains, will the memory occupied by the ansicode array continue to occupy the memory? Since the array is not created with new, it will not be possible to release it even after assigning a pointer. What should I do?


Solution

  • But one question remains, will the memory occupied by the ansicode array continue to occupy the memory?

    C-style arrays have automatic lifetime, they will get destroyed after the local scope ends, so it is undefined behavior to try to do anything with them after the function has returned, you should consider using a container like std::string:

    std::string setFore(const short arg) {
         return "\033[38;5;" + std::to_string(arg) + "m";
    }