c++ - const char * pointing to same memory location -
i trying break string integer , characters using below codes. in first section on immediate printing got right output later wrong.
int lottery::calcinvodds(string ruleconstraint){ const char * sorted; const char * unique; string temp; size_t pos; temp = ruleconstraint; pos = temp.find_first_of(" "); sorted = temp.substr(0,pos).c_str(); cout << temp << endl; cout << "s = " << sorted << endl; temp = temp.substr(pos+1); unique = temp.substr(0,pos).c_str(); cout << "u = " << unique << endl; cout << "sorted = " << sorted[0] << " " << "unique = " << unique[0] << endl<<endl; return 0; } output this:
t f s = t u = f sorted = f unique = f f t s = f u = t sorted = t unique = t but after replacing const char * array char sorted[2] , temp.substr(0,pos).c_str(); *temp.substr(0,pos).c_str(), correct output displayed. reason of behaviour?
sorted = temp.substr(0,pos).c_str(); this isn't going work. temp.substr(0,pos) returns temporary string, .c_str() gets pointer contents, , after statement completes temporary string freed, making sorted point freed memory.
your best option not bother converting const char* , instead change sorted , unique strings. things work expect, because strings persist until function exits.
int lottery::calcinvodds(const string& ruleconstraint){ size_t pos = ruleconstraint.find_first_of(" "); string sorted = ruleconstraint.substr(0, pos); // above line rewritten as: // string sorted(ruleconstraint, 0, pos); cout << ruleconstraint << endl; cout << "s = " << sorted << endl; // -- not sure want, it's code does. #if 1 string unique = ruleconstraint.substr(pos + 1, pos); // -- maybe meant #else size_t pos2 = ruleconstraint.find_first_of(" ", pos + 1); string unique(ruleconstraint, pos + 1, pos2 - pos - 1); #endif cout << "u = " << unique << endl; cout << "sorted = " << sorted[0] << " " << "unique = " << unique[0] << endl << endl; return 0; }
Comments
Post a Comment