【问题标题】:c segmentation fault due to duplicacy in structure in functionsc 由于功能结构重复导致的分段错误
【发布时间】:2015-02-12 18:42:24
【问题描述】:

程序第一次运行正常,但是如果我们要添加另一本书的详细信息,我输入第一个属性后会出现分段错误

int main()
{
    float count_tot=0,profit_tot=0;
    char option='y';
    fflush(stdin);
    struct book b;
    while(option!='n')
    {
        b=getinput();
        display(b);
        b.need= calcneed(b);
        b.profit=calcprofit(b);
        printf("Need To Order:%d\n",b.need);
        printf("Total Cost:%f\n",(b.need-b.qtyonhand)*b.price_sin);
        printf("do another book(Y/n)");
        scanf("%c",&option);
        option=getchar();
        count_tot+=(b.need-b.qtyonhand)*b.price_sin;
        profit_tot+=b.profit;
    }
    drawline();
    printf("TOTAL PROFIT:%f\n",profit_tot);
    printf("TOTAL COST:%f\n",count_tot);
    return(0);
}

struct book getinput
{
    struct book b;
    scanf("%d",&b.book_code);
    ...
    ...
} //the function contains a number of scanf functions

【问题讨论】:

  • 缩进很可怕,很容易遵循代码流
  • 请贴出struct book的定义和getinput的完整代码。

标签: c function memory segmentation-fault structure


【解决方案1】:

您正在函数getinput 中创建一个局部变量并查看其用法,您将其返回给调用者。您最好将结构作为参数传递并将数据读入该结构。当函数终止时,结构的本地副本将被销毁,除非您使用动态内存分配。

【讨论】:

  • 两件事,在处理结构时,它们应该只作为参数传递和返回,以创建完全可移植的代码。并非所有编译器都可以返回结构类型。此外,您在 main 中遇到了一个错误,您将 %c 扫描到 &option 然后下一行读取 option=getchar ();
  • 谢谢...如果我使用其中任何一个语句...它会被跳过并且 'option' 被初始化为换行符,因为它已经存在于缓冲区中
猜你喜欢
  • 2016-03-30
  • 1970-01-01
  • 2013-01-24
  • 2017-09-06
  • 2022-11-23
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多