简体   繁体   中英

Initialize a const char* Array

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?

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM