Struct Casting

Posted By: Rei_Ayanami

Struct Casting - 02/25/12 19:42

Hello!

I possibly just discovered a bug:

When I am casting a void * to a struct pointer and then try to access an element, it does not return the desired member. When I however create a struct pointer and assign this pointer to the void * and then access the members, everything is okay. Both versions work in C++ (tested by copy/paste)

The problem occurred this way:
I have a struct that contains a void pointer (and some other things). The void * points to a struct instance. The struct, it points to, consists of 2 ints.
The following code does not work, and returns the same variable diags the same variable two time.
Code:
diag_var("\nUnscaledScreenWidth	-> %.0f", (((ESscreenStruct*)testDefStruct->specific)->unscaledScreenWidth));
diag_var("\nUnscaledScreenHeight-> %.0f", (((ESscreenStruct*)testDefStruct->specific)->unscaledScreenHeight));



However, this does work and returns the real content of the second variable:
Code:
ESscreenStruct *tempStruct = testDefStruct->specific;
diag_var("\nUnscaledScreenWidth	-> %.0f", tempStruct->unscaledScreenWidth);
diag_var("\nUnscaledScreenHeight-> %.0f", tempStruct->unscaledScreenHeight);




As already said, I am not sure if I am wrong, but I assume that the code is right, as it works in C++.

Thanks,
Marian Frische
Posted By: Superku

Re: Struct Casting - 02/25/12 20:19

Have you tried
(ESscreenStruct*)(testDefStruct->specific)
instead of
(ESscreenStruct*)testDefStruct->specific
?
Posted By: Rei_Ayanami

Re: Struct Casting - 02/25/12 20:25

Yes, that does not work either.

(Also not: ((ESscreenStruct*)(testDefStruct->specific)))
Posted By: SchokoKeks

Re: Struct Casting - 02/25/12 23:53

EDIT: misunderstood you, sry
Posted By: jcl

Re: Struct Casting - 02/27/12 14:49

Make sure you placed the parentheses at the correct places. Otherwise you have a good chance of casting the wrong struct.

Don't write this:

(ESscreenStruct*)testDefStruct->specific

Correct is either this:

((ESscreenStruct*)testDefStruct)->specific

Or this:

((ESscreenStruct*)(testDefStruct->specific))

dependent on what you want to cast.
Posted By: Rei_Ayanami

Re: Struct Casting - 02/27/12 15:12

I want to cast the "specific" to ESscreenStruct, which should work by your last example, but actually does not.
Posted By: jcl

Re: Struct Casting - 02/27/12 16:10

I can not confirm such a problem - can you please post a simple example?
Posted By: Rei_Ayanami

Re: Struct Casting - 02/27/12 16:21

I cannot reproduce that behavior in a small script (going to take a look again later however).

(The whole system is external btw, I only access it via liteC)
© 2024 lite-C Forums