• C

RE: Convert an array of floats to an array of doubles

Hi there,

Could some one show me an example of converting an array of floats to an array of doubles.

I no VERY little about C and am just trying to hack some code to get a function to work.



Who is Participating?
PerryDKConnect With a Mentor Commented:
float floatArray[100];
  double doubleArray[100];

  int i;

  //to convert from a float to a double no casting is needed
  for(i = 0; i < 100; i++)
    doubleArray[i] = floatArray[i];

  //now if your converting from a double to a float
  //you will need to do some type casting
  //be aware that some data may lost as
  //floats can store as much precision as doubles
  for(i = 0; i < 100; i++)
    floatArray[i] = (float)(doubleArray[i]);

  //you can technically do this in C
  //although some compilers will give you a warning
  //saying somthing about possible loss of precision
  //It is legal in C and will compile though
  for(i = 0; i < 100; i++)
    floatArray[i] = doubleArray[i];
Can you try just casting the floats to doubles ..

for example
float a ;
double b ;

a = 1.2 ;

b = (double) a;

do this in a for loop for the whole array


guess both of us replied at the same time. :)
if you have a function say
void foo(double* doubleArray)

you can not pass in an array of floats

like wise if you have a function
void foo2(float* floatArray)

you can not pass in an array of doubles

The reason for this is floats and doubles are of different sizes.  Most systems floats are 32 bytes wile doubles are 64 bytes.  

So if you have an array of floats and need to pass them to a function that requires an array of doulbes you will have to actually convert your float array to a double array and then pass that in.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.