Const float union ptr in Bradski & Kaehler "OpenCV Training" Example 3-9

In " OpenCV Training " by Gary Bradsky and Adrian Kaehler, there is a section on the structure of the CvMat matrix, which contains the following code example (it is Example 3-9: Summing all the elements in a single-channel matrix)

float sum( const CvMat* mat ) { float s = 0.0f; for(int row=0; row<mat->rows; row++ ) { const float* ptr = (const float *)(mat->data.ptr + row * mat->step); for(int col=0; col<mat->cols; col++ ) { s += *ptr++; } } return( s ); } 

There are a few things that I don’t understand about this code, but they may be the result of the fact that I have not used C for many years, and not OpenCV issues.

  • Why const ? Since ptr increases further in the function, I don’t understand why it is declared const.

  • Why .ptr ? The authors note that "when calculating a pointer into a matrix, remember that the matrix data element is a union. Therefore, when it refers to this pointer, you must specify the correct union element to get the correct pointer type." So, why not use a member of the union fl with type float* so that the line of code is

     float* ptr = mat->data.fl + row * mat->step; 

instead of taking ptr with uchar* type and requiring extra casting?

0
c opencv
Oct 06 '13 at 7:50
source share
1 answer

Why const? Since ptr increases later in the function, I don’t understand why it is declared const.

Because it is not a const pointer, but an object that it points to. What you are talking about will be written as float *const ptr , but as you can see, ptr not declared as such.

Why .ptr?

Because the union may not have the same size as the float . Imagine this array:

  union * union * union * union * +0 +1 +2 +3 (correct) +----------------+----------------+----------------+ union boundaries: | union | union | union | +----------------+----------------+----------------+ float boundaries: | float |junk| float |junk| float |junk| +----------------+----------------+----------------+ ^ ^ ^ ^ ^ float * float * float * float * float * +0 +1 +2 +3 +4 ^--------- these are all wrong ----------^ 

If you get a pointer to the first float and apply the arithmetic of the pointer on it, this will lead to incorrect results if union greater than float .

+1
06 Oct '13 at 8:01
source share



All Articles