Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typecasting char pointer to float in C [duplicate]

Tags:

c

casting

parsing

I have a flat file with the ff data:

date;quantity;price;item

I want create a data record using the following struct:

typedef struct {
  char * date, * item;
  int quantity;
  float price, total;
} expense_record;

I created the following initializing method:

expense_record initialize(char * date, int quantity, char *price, char *item) {
  expense_record e;
  e.date = date;
  e.quantity = quantity;
  e.item = item;
  /* set price */
  return e;
}

My question is how to set the price as float (as required by the struct) from the char *price. The closest I got, i.e. without generating a compiler error was

 e.price = *(float *)price

but this results in segmentation faults.

Thanks!

like image 290
DannyClay Avatar asked Aug 09 '26 03:08

DannyClay


2 Answers

You are looking for the strtod strtof library function (include <stdlib.h>). Relatedly, if the calling code uses anything other than strtoul to convert quantity from text to an int, that is probably a bug (the only exception I can think of would be, if for some reason quantity can be negative, then you would want strtol instead).

like image 187
zwol Avatar answered Aug 11 '26 17:08

zwol


To convert text to a float, use strtof(). strtod() is better for double.
Your initialize routine likely wants a copy of the `date, etc.
A suggested improved routine follows:

expense_record initialize(const char * date, int quantity, const char *price, const char *item) {
  expense_record e;
  char *endptr;
  e.date = strdup(date);
  e.quantity = quantity;
  e.item = strdup(item);
  if (!e.date || !e.item) {
    ; // handle out-of -memory
  }
  e.price = strtof(price, &endptr); 
  if (*endptr) {
    ; // handle price syntax error
  }
  return e;
}

BTW: Recommend an additional change to pass into your initialization the destination record, but that gets into higher level architecture.

like image 33
chux - Reinstate Monica Avatar answered Aug 11 '26 17:08

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!