c++ - Storing char pointers then fill it later on -
i'm having small issue here, i'm storing char pointer ( rather array ), in void pointer following:
char result[255]; cevariable result_var(cetype::string, result);
now result_var passed on engine, stored pointer, variable structure accessed later on: ( m_pdata void*, pointing char array )
strcpy((char*)pvar->m_pdata, "42");
but no data written it, , i'm sure points result array, checked addresses. maybe have gotten wrong in understanding of void pointers, following seems work: ( testing )
char dest[255]; void*ptr = dest; strcpy((char*)ptr, "asdsa"); std::cout << dest;
the result array turns unreadable format, random memory. maybe never written to. question may issue be?
edit: cevariable::
class cevariable { public: cevariable() {} cevariable(cetype t, void* mem) { m_type = t; m_pdata = mem; } // variable type cetype m_type; // variable data ptr void* m_pdata; };
the result not go out of scope executed in 1 function.
thank time.
your cevariable::m_pdata
pointer. has no space reserved string.
you should first allocate memory string (e.g. using new[]
), , strcpy()
source string reserved space:
// dynamically allocate memory new[]. // string "42", it's 3 chars: '4', '2' , terminating nul '\0'. // generic string, may want use strlen(s)+1. pvar->m_pdata = new char[3]; // copy string strcpy(static_cast<char*>(pvar->m_pdata), "42"); // don't forget release string memory delete[] // when it's no longer needed. // (e.g. in cevariable's destructor.)
note in c++ should use c++-style casts instead of c-style casts.
the problem stack-allocated buffer char result[255]
destroyed when variable goes out of scope. instead, if allocate string memory new[]
(from heap), memory still available after scoped-ending brace }
. memory released when call delete[]
on pointer.
Comments
Post a Comment