Ask Your Question

const float union ptr in Bradski & Kaehler's “Learning OpenCV” Example 3-9

asked 2013-10-06 02:53:35 -0500

dumbledad gravatar image

updated 2013-10-06 02:55:02 -0500

In "Learning OpenCV" by Gary Bradski & Adrian Kaehler there is a section on the CvMat matrix structure that contains the following example code (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 couple of things I do not understand about this code, but they may be the result of me not using C for many many years rather than OpenCV questions.

  1. Why const? Since ptr is incremented later in the function I do not understand why it is declared const.

  2. Why .ptr? The authors point out that "When computing the pointer into the matrix, remember that the matrix element data is a union. Therefore, when de-referencing this pointer, you must indicate the correct element of the union in order to obtain the correct pointer type." So why not use the union member fl with type float* so that the line of code would be

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

instead of taking ptr with type uchar* and requiring an additional cast?

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted

answered 2013-10-06 07:26:38 -0500

Michael Burdinov gravatar image
  1. There two meanings to const pointer: pointer itself is constant or pointed value is constant. It depends on location of const key-word (before or after asterisk). In this case the pointer itself is not constant (you see it changing). But the values it points to are constant so you can't alter them by mistake while you are working with them. I recommend you to read more about const in C++. This is important and not trivial issue.

  2. step between following lines in given in bytes. If you perform your calculation in the way you described, you will step four time more than required. Notice that cast to float is performed on (mat->data.ptr + row * mat->step) not just (mat->data.ptr).

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2013-10-06 02:53:35 -0500

Seen: 179 times

Last updated: Oct 06 '13