Consider these functions:

void OperateOnDoublePointer(double* a)
{
  std::cout << a[0] << std::endl;
}

void OperateOnFloatPointer(float* a)
{
  std::cout << a[0] << std::endl;
}

This works as expected:

double* c = new double[1];
  c[0] = 3.3;
  OperateOnDoublePointer(c);

but when I try to do this:

double* c = new double[1];
c[0] = 3.3;
OperateOnFloatPointer(c);

It complains that it can't convert double* to float*.

I tried to tell it that was ok:

OperateOnFloatPointer(static_cast<float*>(c));

but it said can't cast double* to float*.

If I do this, it works:

float* d = new float[1];
  d[0] = c[0];
  OperateOnFloatPointer(d);

but I'd have to loop over all elements. Is there a single line way to do this (pass a float* to a function expecting a double*, or visc versa)?

Thanks,

Dave

>it said can't cast double* to float*
Certainly not with static_cast. For that you need either reinterpret_cast or a C-style cast. Either way, it's not a very good idea to blindly jump from a larger type to a smaller type. At the very least, a preliminary test for overflow would be a good idea.

With reinterpret_cast it compiles, but the output is garbage.

What do you mean an overflow test? I'm not concerned about the loss of precision - 1.2 = 1.2 as a float or a double :)

Dave

>With reinterpret_cast it compiles, but the output is garbage.
I'm not surprised. Let's not forget that you're working with pointers and not float/double directly.

>What do you mean an overflow test?
Let's make it easier to visualize. Would you be wary about saying a = b when a is a short and b is a long int? If you answer "no", I'll whack you with a cardboard tube.

commented: So violent!! +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.