简体   繁体   中英

Why am I getting random outputs from this string to char conversion?

I'm just trying to do a string conversion to char (more precisely char*) but for no reason, I got different outputs if I run the code on codeBlocks or in my project. So on codeBlocks, I run this :

#include <iostream>
#include <string>

using namespace std;

int main()
{
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable ;
}

I got this output : 在此处输入图片说明

And in my project, I run the same lines but in an event handler :

void RePROGUIUser::applyOptions(wxCommandEvent& event) {
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable;
}

Output : 在此处输入图片说明

So I have to push a button on my GUI for that to happen but it really shouldn't change anything (and I was skeptical about putting the wxWidget tag here).

Any idea someone ?

You code has undefined behavior , means anything is possible. Note that the null terminator is '\\0' but not '\\n' . So change

writable[stlstring.size()] = '\n';

to

writable[stlstring.size()] = '\0';

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