frank10 Posted May 28, 2012 Share Posted May 28, 2012 I have this code in VC2010: typedef struct CvScalar { double val[4]; } CvScalar; CvScalar cvScalarAut( double val0, double val1 , double val2 , double val3 ){ CvScalar scalar; scalar.val[0] = val0; scalar.val[1] = val1; scalar.val[2] = val2; scalar.val[3] = val3; return scalar; } When I call the func like this: CvScalar test = cvScalarAut( 234,10,45,200); printf(" %f %f %f %f %f \n",test, test.val[0], test.val[1],test.val[2],test.val[3]); I get: 234,10,45,200,234 Why 'test' correspond to the first array's value and 'test.val[0]' to the second and not the first? And test.val[3] gives again the first value? Link to comment Share on other sites More sharing options...
danielkza Posted May 28, 2012 Share Posted May 28, 2012 (edited) First of all, your code is invalid: you're passing a structure as the first parameter to printf() while it is expecting a float. printf() works by looking at the string specifier and pulling the appropriate amount of data from the stack, which you wrongly populated with the contents of the structure *twice*. Remember that in the default C calling convention arguments are passed in reverse order, so they can be popped in left-to-right order by the callee, and that you passed the structure *as a single piece*. This is how the stack will look, from top to bottom, right before control is passed to printf(): // top test.val[0] test.val[1] test test.val[2] / test.val[3] / test.val[0] <= test.val[0] test.val[1] <= test.val[1] test.val[2] <= test.val[2] test.val[3] <= test.val[3] printf() will then pop 5 floats from the stack and print them, which explains the behavior you are seeing. The lesson to take is *don't pass printf() anything but exactly what it is expecting*, which *is not* a struct and 4 floats, but *exactly 5 floats*. Edited May 28, 2012 by danielkza JohnQSmith and jaberwacky 2 Link to comment Share on other sites More sharing options...
frank10 Posted May 29, 2012 Author Share Posted May 29, 2012 Thank you, now it's clear. Link to comment Share on other sites More sharing options...
Shaggi Posted May 29, 2012 Share Posted May 29, 2012 One of the "features" of cdecl lol. very nice answer danielkza. Ever wanted to call functions in another process? ProcessCall UDFConsole stuff: Console UDFC Preprocessor for AutoIt OMG Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now