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

Started by
1 comment, last by Keermalec 21 years, 5 months ago
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?
Advertisement
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.
~neoztar "Any lock can be picked with a big enough hammer"my website | opengl extensions | try here firstguru of the week | msdn library | c++ faq lite
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

This topic is closed to new replies.

Advertisement