Jump to content

C struct with array


frank10
 Share

Recommended Posts

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

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 by danielkza
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...