Friday, 15 April 2011

Array data lost when returned from function in C++ -



Array data lost when returned from function in C++ -

i'm sure novice question book i'm studying shows how encode structurs buffer. examples simple types only. i'm trying take 1 step farther using dynamic array.

my problem after calling encode(), calling function can see value of bodylen value of "body" lost. doing wrong?

the pseudo code:

struct outdata { uint32_t bodylen; // length of body uint32_t *body; // array of body elements }; int encode(uint8_t *buffer, int size) { // set buffer info construction layout outdata *mydata = (outdata *)buffer; // junk info (a nice 10101010...) uint32_t junk = 2863311530; // populate body uint32_t bodydata[size]; (int i=0; i<size; i++) { bodydata[i] = htonl(junk); } // set buffer mydata->bodylen = size; // works mydata->body = bodydata; // blank calling function ... }

thanks!

bodydata local variable, setting mydata->body point it. after encode returns, bodydata destroyed , *mydata->body undefined.

to fix, need deep re-create of contents of bodydata mydata->body after allocating space (with new[]). , need sure delete[] later.

c++

No comments:

Post a Comment