【问题标题】:Segmentation fault with method in CC中方法的分段错误
【发布时间】:2014-11-07 19:51:00
【问题描述】:
#include<stdio.h>
int calc_perc(int r){

        float A, B, C, OTHER;
        int fullSections, leftover;
        const int FULLCLASS = 25;

        fullSections = r/FULLCLASS;
        leftover = r - (FULLCLASS*fullSections);
        A = r*0.30;
        B = r*0.25;
        C = r*0.15;
        OTHER = r*0.30;

        printf("\nEnrollment: %d students\n", r);
        printf("Full sections: %d\n", fullSections);
        printf("Left over: %d students\n", leftover);

        printf("\n      Students expected to recieve an A: %0.2f ", A);
        printf("\n      Students expected to recieve a B: %0.2f ", B);
        printf("\n      Students expected to recieve a C: %0.2f ", C);
        printf("\n      Students expected to recieve some other grade: %0.2f\n\n", OTHER);

        printf("=======================================\n\n");
}

int main(void)
{

        int students1, students2, students3;

        printf("Elijah Grote\n");
        printf("\nEnter three enrollments on one line: ");
        scanf("%d %d %d", students1, students2, students3);
        calc_perc(students1);
        calc_perc(students2);
        calc_perc(students3);
        return 0;
}

我认为错误发生在 calc_perc 或 scanf 中...但我无法弄清楚它是哪个以及为什么会这样做...它编译干净,但是当我输入学生 1、2 和 3 的数字时,它给了我一个分段错误。我使用 Unix,当我执行 a.out 并在它要求 3 个数字后输入它: 56 ^H^H 它打印出正确的格式,但没有正确的数字......与错误的内存分配或指针不好?

感谢任何帮助,

谢谢

【问题讨论】:

    标签: c function segmentation-fault scanf calling-convention


    【解决方案1】:

    函数scanf 需要每个目标变量的地址(否则它将如何设置?)。

    改变这个:

    scanf("%d %d %d", students1, students2, students3);
    

    到这里:

    scanf("%d %d %d", &students1, &students2, &students3);
    

    附带说明,您已声明函数 calc_perc 以返回 int,但它不返回任何内容。

    【讨论】:

    • OP 应该考虑使用 -Wallgcc - 编译器会警告这个问题。
    • @MichaelBurr:你基本上是对的,但我相信手头的问题意味着 OP 在进入编译器配置之前还有很多基本的东西需要学习。
    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 2014-08-28
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多