Casting pointer type

Asked by At

I see a piece of OpenCV code:

float *huedata = (float *);

where hue is created by Mat hue(Size(640,480),CV_32FC1)

The returns a pointer uchar*, but I don't see why put (float *) instead of (float) in front of and also why need to cast to float rather keep using uchar?. Anyone can help explain this?

1 Answers

Jonathan Heard On Best Solutions

A pointer to a float is a completely different type of value to a float itself. This can be hard to grasp if you aren't used to pointers, so let me explain. (as a pointer) holds a number which is an index to a location in memory. Let's say, for instance, that holds the number 187. That means that it represents the 187th byte of memory. Now, lets say that the value stored at that memory location is the value 3.14. What you actually care about that value 3.14.

Here is what you suggested:

float huedata = (float);

After this line, you will have a variable huedata which stores the number 187, since that is what was copied from The value 3.14 is completely ignored.

Here is what was originally written:

float *huedata = (float *);

After this line, you will have a variable huedata which stores the number 187, but is a pointer, which means it points to the memory location where you can find the value 3.14. Thus you still have access to the value 3.14, which is what you really care about.

As for casting from (uchar*) to (float*). Since pointers are just numbers representing memory locations, casting from one pointer type to a different one just means considering the value at that memory address a float instead of a uchar. This is probably done because can represent different kinds of values in different circumstances, so they typed it as uchar, expecting the user to retype based on the circumstance.