Archived

This topic is now archived and is closed to further replies.

Keermalec

Difference between "data* ModifyData()" and "void ModifyDat(data*)"?

Recommended Posts

What is the difference between these two, seemingly similar methods of modifying data? data* ModifyData(void); and void ModifyData(data*); The first one is used as in: datatype* data; data = ModifyData(); The second one as in: datatype* data; ModifyData(data); I prefer the second way but in certain cases I get a runtime memory error when I use it. I am obviously missing some memory management notion here. Can someone explain?

Share this post


Link to post
Share on other sites
The first method is ok for getting data from somewhere, but not for modifying, as no information on the original data is passed to the function.

Your memory errors could be almost anything, but making sure data isn''t NULL would be a start. Debug your prog and place a breakpoint in your code and check what''s going on.

Share this post


Link to post
Share on other sites
The first method creates an object of type datatype, and returns a pointer to it. The second method modifies an existing datatype object. They are both very different.

An implementation and use of the first could be:

data *CreateData(void)
{
datatype *data = new datatype;
*data = ... something ...
return( data );
}

datatype *data = CreateData();
... do something with data ...


The second one uses an existing object:

void ModifyData(datatype *data)
{
*data = ... something ...
}

datatype data;
ModifyData(&data);
... do something with data ...


Note that this will crash:
datatype *data;
ModifyData(data);

as no data object has been created, just a pointer to an undefined one. Dereferencing the pointer to a non-existant onbject in ModifyData() will crash the code.

/ Yann

Share this post


Link to post
Share on other sites