1

I have an integer array, of which, I know the first 4 bytes are a float the secon 4 bytes are another float and so on; to extract float numbers I use a float pointer like this:

uint8_t  l_buffer[17];
float32  num1 = *(float*)&(l_buffer);
float32  num2 = *(float*)&(l_buffer[4]);

and all works perfectly, but I don't understand why!!!! In fact I tried to use the pointers without the '*':

float32  num1 = (float*)&(l_buffer);
float32  num2 = (float*)&(l_buffer[4]);

but it doesn't work. Sorry, but (float*)&(l_buffer) is not a cast to a floating pointer to the first location of l_buffer array ? Why I need to add the '*' ?

Orace
  • 7,822
  • 30
  • 45
Davide
  • 33
  • 2

1 Answers1

0

When you write (float*)(anystuff)you got a float pointer.

So yes (float*)&(l_buffer) is a cast to a float pointer to the first location of the array.

But there is no explicit conversion from a float pointer to a float so this will not work:

float  num1 = (float*)&(l_buffer);  // error (float*) is not (float)

But you can want to read the pointed value like float f = *(pFloatPointer) , and that why thus this will work:

float  num1 = *(float*)&(l_buffer); // ok *(float*) is a (float)

Also cast to a float* give you facilities for indexing:

float f1 = *(float*)&(l_buffer[4]);    // 4th element of a uint8_t array
float f2 = ((float*)l_buffer)[1];      // 1th element of a float array
                                       // So f1 == f2
Orace
  • 7,822
  • 30
  • 45
  • @AdrianLeonhard, in this case, because it is cast to a float* it will have no effect, you can see an explanation here http://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c – Orace Feb 25 '15 at 12:30