【发布时间】:2021-06-10 02:18:23
【问题描述】:
我正在尝试完成一个练习,该练习应该有助于巩固我对指针和结构的知识,其中结构指针作为参数传递给函数。提供的解决方案使用scanf 来获取用户输入并且效果很好,但是由于此功能(方法?)被认为是不安全的,我正在尝试寻找一种替代方法来实现相同的结果。
问题是一个浮点类型的结构成员导致了分段错误,我将strtof() 与fgets() 结合使用,将用户输入从char 转换为float。我之前看过一些我认为可能有用的字符串函数(atof() 和atoi() - 将此函数的返回值转换为浮点数),但无法成功地实现转换。正如我所提到的,我正在尝试使用strtof(),但同样,我没有成功。
这是一个问题的例子:
#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);
}
我知道我的实现中存在错误,但我不知道如何解决它们。我使用了各种调试技术(printf、IDE 内置调试器、lldb),但我发现即使不是不可能,也很难解释结果。我将不胜感激。
【问题讨论】:
-
你不需要为
pEnd分配内存。看看它是如何使用的here -
使用标签来传达语言。
-
Den,有时作为文本的浮点值比
SIZE 50字符多得多。 500个怎么样? -
@Barmar 感谢您提供的示例,这些示例也参考了文档。我需要仔细研究一段时间才能更好地熟悉
strtof()。我对malloc的使用是为了寻找无效内存访问问题的解决方案(以及对我尝试使用的工具的理解不足)的绝望尝试。 -
@Den 他的意思是你不需要把 [c] 放在问题标题中,因为它已经在标签中了。
标签: c pointers struct segmentation-fault type-conversion