C中的方法分段错误

时间:2014-09-13 22:53:54

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

#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它打印出正确的格式,但没有正确的数字...与错误的内存分配有关或者一个糟糕的指针?

感谢任何帮助,

由于

1 个答案:

答案 0 :(得分:2)

函数scanf需要每个目标变量的地址(如何将其设置为某些内容?)。

改变这个:

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

对此:

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

作为旁注,您已声明函数calc_perc返回int,但它不会返回任何内容。