Chris Haynes wrote in news:ba**************************@posting.google.c om:
Hello all,
I have a structure:
Did you cut-n-paste this from some C code, the typedef is
unnessasery and you dont even use it.
typedef struct UVstruct {
float u, v;
} uv;
struct UVstruct {
float u, v;
};
Would do just fine.
Inside a function (A) i declare a pointer to an instance of this
structure:
UVstruct *pUV;
then from within the same function (A) i call another function (B)
that takes as one of its parameters the pointer declared above.
From within functionB i dynamically declare an array (pUVlocations is
the name of the passed pointer pUV within B):
change B from say:
void B( UVstruct * pUVlocations );
To:
void B( UVstruct * & pUVlocations );
pUVlocations = new UVstruct[number];
This will now assign to the pointer you passed in, not a copy of
it.
Still in B, I fill pUVlocations with some data. At the end of the
function pUVlocations contains all the data it should, and i do not
free pUVlocations.
However when the program has passed back to A, when I try to access
pUV it contains rubbish.
What am I doing wrong? Why does pUV not contain the data it was given
within B?
Because you changed the value of a *copy* not the original.
void does_nothing( int i )
{
/* this just changes the value of the *copy* that was passed
*/
i = 2;
}
int main()
{
int j = 3;
does_nothing( j ); /* passes a copy of j */
// j == 3 still.
}
I'd suggest you change B so that it returns the pointer, since
logicaly B() is creating the array.
UVStruct *B( /* whatever */)
{
UVStruct * pUVlocations = new UVstruct[number];
/* init ... */
return pUVlocations;
}
void A()
{
UVStruct *b = B();
}
Also consider using std::vector<> instread of trying to create
and manage your own array's.
#include <vector>
struct UVStruct {/*...*/};
either:
void B( std::vector< UVstruct > &uv_vect /* ,... */ )
{
uv_vector.resize( number );
/* init ... */
}
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/