2021年3月11日星期四

Trying to convert type char to type float, but gettng segmentation fault

I am attempting to complete an exercise that should help to solidify my knowledge of pointers and structs, where a struct pointer is passed to a function as a parameter. The provided solution uses scanf to obtain user input and works very well, but as this function (method?) is considered unsafe, I am attempting to find an alternative way of achieving the same result.

The issue is that one struct member, being of type float, is causing a segmentation fault, where I am converting user input from char to float by using strtof() in conjunction with fgets(). I have previously looked at a few string functions that I thought might be helpful (atof() and atoi() - casting this function's return value to float), but have been unable to successfully implement the conversion with those. As I mentioned, I am attempting to use strtof(), but again, I have not been successful.

Here is an example of the problem:

  #include <stdio.h>  #include <stdlib.h>  #include <ctype.h>    struct Stock {      float cost;  };    #define SIZE 50    void ReadIn(struct Stock *purchase);  void PrintOut(struct Stock *receipt);    int main ()  {      // instantiate struct type      struct Stock product;      // instantiate struct type pointer      struct Stock *pItem;        pItem = &product;        if (pItem == NULL)      {          exit(-1);      }      else      {          ReadIn(pItem);            PrintOut(pItem);      }        return 0;  }    //---- Function Definitions ----//    // read function  void ReadIn(struct Stock *purchase)  {      char pNum[] = {0};      char *pEnd;        printf("\nEnter the price: ");      fgets(pNum, SIZE, stdin);        pEnd = (char *) malloc(SIZE * sizeof(char));        purchase->cost = strtof(pNum, &pEnd);  }    // print function  void PrintOut(struct Stock *receipt)  {      printf("\nPrice: %.2f\n", receipt->cost);  }    

I know there are mistakes in my implementation, but I don't know how to resolve them. I have used various debugging techniques (printf, IDE built-in debugger, lldb), but I find the results difficult, if not impossible, to interpret. I would appreciate some help.

https://stackoverflow.com/questions/66593548/trying-to-convert-type-char-to-type-float-but-gettng-segmentation-fault March 12, 2021 at 10:58AM

没有评论:

发表评论