Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Type conversion problem

Status
Not open for further replies.

coetzw01

Programmer
Jul 7, 2005
1
US
As a rookie programmer I'm struggling with type conversion from double to float. I know the easiest is to declare both as double, but that won't work. I have one libabry in single- and another in double precision. The questions are indicated below:
======================================

main ()
{

int i;
float* t;
double a;

typedef struct {
double* user_t;
} lm_data_type;

lm_data_type data;

t=(float *)malloc( (N_POINTS+1)*sizeof(float));

// generate data
for (i=0; i<N_POINTS; i++) {
t = (double) i ;
}

data.user_t = (double*) t; // how can I correctly do the type conversion here?

for (i=0; i<N_POINTS; i++) {
a = data.user_t; // Is this right????????
printf ("%6.3f %6.3f \n", t, a );
}

free(t);
return 0;
}
 
1. PLEASE, use CODE tag for your snippet (see Process TGML link on the form).
2. There are two (or more;) different questions in your one.
No need in special (explicit) conversion between double and float values: C language implicitly makes it for you. For example, in printf() arglist your compiler implicitly converts float t value to double (warning: use %lf specificator, not %f for doubles in scanf arglist).

Another case - convert pointer to float in pointer to double. It's wrong to cast pointer with (double*). You must allocate new array of doubles then copy the float array contents (element by element).

In the snippet above you try to deceive your compiler (and yourself) with casting but your float array still contains floats, not doubles. So you have wrong values when extract elements via double pointer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top