开发者

problem in passing parameters in c++ (pointers confused me)

I've write a procedure which will store some data inside a structure and the I will pass the structure to other procedure like below

slotUpdate(Datas);

whereas I've defined the structure like :

someNameSpace::stuData Datas;

after passing the structure to slotUpdate again I'll pass it to another procedure but this time as a parameter and as (void *) like following :

开发者_如何学编程
updateDB(void * parameter){
anotherNameSpace::someFucntion((stuData *) parameter);
}

note : I pass the Datas to updateDb such this : updateDB(&Datas);

and into someFunction when I try to retrieve a data from this structure I'm not successful and I will get wrong data , something garbage :-?

what is my problem here?


In your call to slotUpdate you are passing "Data" not "&Data". You havn't given us the declaration of slotUpdate, but it can be declared in one of two ways:

void slotUpdate(stuData& Data);
void slotUpdate(stuData Data);

If the function IS defined the first way, then I don't understand. The 2nd way however is a pass by value semantic :- slotUpdate will be writing to a local copy of the Data struct, this passed in struct will not be updated and so, will contain the same garbage it started with when slotUpdate returns. Which you will then pass to other functions.

Change your definition of slotUpdate to one of the following:-

void slotUpdate(stuData* pData);
void slotUpdate(stuData& Data);

I prefer the first form because it makes explicit that you are passing in a pointer to the struct you want changed. The 2nd form makes it difficult to understand - as is made obvious in your post - whether pass by value or pass by reference semantics are being used.


I can't tell from what you've written what is happening, and in what order. Is the failure happening inside someFucntion()?

Is the structure supposed to be filled in by slotUpdate(), and if so, did you define slotUpdate() to accept a reference parameter (e.g.,void slotUpdate(someNameSpace::stuData &Datas);?)


Is it possible that you have two different StudData in both namespaces and you're casting to the incorrect one when you're using it?

Another point, just for imporvement: in C++ it is not a good practice to use C style casts (like (data*)), it is better to use static_cast/dynamic_cast, etc - where appropriate. So you could use static_cast() in your example.

Also, casting to void* and backward was ok in C since that was what enabled abstract/generic programming, but C++ has other, better, mechanisms for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜