c++ - assigning values to structure of a class using class object -
i have got strange problem. here code: header file
namespace test { class loadconfigdata { struct control_params { char active[]; char suspended[]; char erased[]; }*ctrl_params; bool loadconfig(); }; }; main.cpp
using namespace std; using namespace test; namespace test { extern loadconfigdata *loadconfigdataobj; loadconfigdata *loadconfigdataobj = new loadconfigdata; }; int main() { loadconfigdataobj->loadconfig(); cout <<loadconfigdataobj->ctrl_params->active_status_code_v<<endl; cout <<loadconfigdataobj->ctrl_params->suspended_status_code_v<<endl; cout <<loadconfigdataobj->ctrl_params->erase_status_code_v<<endl; return 0; } bool loadconfigdata::loadconfig() { std::string = "ac"; std::string b = "sp"; std::string c = "er"; loadconfigdata::ctrl_params = new loadconfigdata::control_params; sprintf(loadconfigdataobj->ctrl_params->active,"%s",a.c_str()); sprintf(loadconfigdataobj->ctrl_params->suspended,"%s",b.c_str()); sprintf(loadconfigdataobj->ctrl_params->erased,"%s",c.c_str()); return true; } output:
er er er which means it's printing last copied string each struct member. wrong in code.
the problem don't give character arrays size:
struct control_params { char active[]; char suspended[]; char erased[]; }*ctrl_params; i'm rather surprised compiles; understanding unsized array incomplete type, , couldn't non-static class member. however, compiler @ least (and presumably yours) treats these arrays of size zero, @ same location in memory. therefore, each time write 1 overwrites whatever wrote others. (of course, behaviour undefined since writes outside array bounds).
the simplest solution use std::string represent strings. manage size automatically, , can write active = a rather messing around sprintf (or, more sensibly, strncpy) , hoping don't buffer overrun.
Comments
Post a Comment