Jump to content



Photo

C struct with array


  • Please log in to reply
3 replies to this topic

#1 frank10

frank10

    Polymath

  • Active Members
  • PipPipPipPip
  • 217 posts

Posted 28 May 2012 - 06:46 PM

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?





#2 danielkza

danielkza

    Universalist

  • Active Members
  • PipPipPipPipPipPip
  • 426 posts

Posted 28 May 2012 - 08:51 PM

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, 28 May 2012 - 09:41 PM.

  • JohnQSmith and jaberwocky6669 like this

#3 frank10

frank10

    Polymath

  • Active Members
  • PipPipPipPip
  • 217 posts

Posted 29 May 2012 - 08:11 AM

Thank you, now it's clear.

#4 Shaggi

Shaggi

    Universalist

  • Active Members
  • PipPipPipPipPip
  • 296 posts

Posted 29 May 2012 - 02:44 PM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users