typecasting char pointer to float in C [duplicate]

2019-02-18 21:59发布

This question already has an answer here:

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!

3条回答
Evening l夕情丶
2楼-- · 2019-02-18 22:47

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).

查看更多
该账号已被封号
3楼-- · 2019-02-18 22:59

You are having a segmentation fault because a float have 4 Bytes: when you make *(float *)price you are accesing to the first 4 Bytes of price, so if price´s size is smaller than 4 chars, you will have an error.

I think that the best you can do is read a float instead a char * when you parse the data (as i supose yo do with quantity), for example fscanf (pFile, "%s;%d;%f;%s", &date, &quantity, &price, &item);

or convert to float in initialize with strtod instead of make a cast.

查看更多
来,给爷笑一个
4楼-- · 2019-02-18 23:00

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.

查看更多
登录 后发表回答