0

I'm working in C++17 project, but have to use a C-legacy-library. For this I have to create a const char* array in C-style, but im struggling with the initialization. In particular,

#include <iostream>

int main(int argc, char* argv[])
{
    const int bound = 3;

    const char* inames[bound]{ "" };
    for(unsigned int i = 0; i < bound; i++) {
        const char *number = std::to_string(i).c_str();
        inames[i] = number;
    }

    for(unsigned int i = 0; i < bound; i++) {
        std::cout << "inames["
                  << std::to_string(i)
                  << "] = "
                  << inames[i]
                  << std::endl;
    }

    return 0;
}

returns

inames[0] = 2
inames[1] = 2
inames[2] = 2

as output, which I don't unterstand. I expected the output to be

inames[0] = 0
inames[1] = 1
inames[2] = 2

Can anyone please help me point me to my error?

0

2 Answers 2

5

You code has undefined behavior.

std::to_string(i).c_str()

You are creating a temporary std::string instance, then getting its internal const char* pointer. At the end of the line the temporary instance is dead, so the pointer is now dangling.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. It helped me to understand my error and find a first bugfix.
2

The problem is you don't have anywhere to actually store the strings themselves, only the pointers to them.

By doing it this way, the strings are stored in std::strings while beeing referenced by the plain C array:

const int bound = 3;
std::vector<std::string> strings(bound);
const char* inames[bound];
for (unsigned int i = 0; i < bound; i++) {
    strings[i] =  std::to_string(i);
    inames[i] = strings[i].c_str();
}

1 Comment

Thank you for your solution. I've got another solution with the help of @VittorioRomeo at first, but yours is way more elegant. I use your solution now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.