didjek
didjek

Reputation: 451

How to cast int pointer to float pointer

I am running cppcheck (c++11) against a library that contains many casts similar to the below:

// Allocates various buffers
int*   i_buffer = (int*)   calloc (500, sizeof (int));
float* f_buffer = (float*) i_buffer;

For these casts, I see the following message:

"portability","invalidPointerCast","Casting between integer* and float* which have an incompatible binary data representation."

What is the correct way to perform the type of cast shown above ? What is the potential consequence of casting the pointer the way it is shown above ?

Upvotes: 0

Views: 1195

Answers (3)

Nick
Nick

Reputation: 471

It's also legitim to use an old style C array by new (which is C++ standard):

float* f_buffer = new float[500];

Be aware to adapt the releasing of that memory to:

delete [] f_buffer;

Type casts should always be avoided to keep a clean code and to allow the compiler to verify correctness of your code.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234885

Strictly speaking the behaviour of your code is undefined due to a strict aliasing violation.

In practice, if int and float are the same size (they are on many desktop platforms although there is some push to move int to 64 bit), then the code will run without error. Although to re-iterate, from the perspective of standard C++ there is absolutely no guarantee of this.

But you should still fix it. Allocating the float array directly is the sensible thing to do:

float* f_buffer = (float*) calloc (500, sizeof (float));

Upvotes: 1

eerorika
eerorika

Reputation: 238471

How to cast int pointer to float pointer

Using reinterpret cast.

But don't try to do that, because the reinterpreted pointer won't be useful.

What is the correct way to perform the type of cast shown above ?

The shown cast is already well defined by itself; it's just not useful to do such cast.

If you need to allocate an array of floats, you can use the following instead:

std::vector<float>(500);

Upvotes: 2

Related Questions