当我运行这段代码时,它返回了Segmentation Fault (core dumped)
。我尝试了很多方法,但我相信我在使用指针方面出了问题。我做错了什么?
要求:每个变量都必须是指针。
#include <stdio.h>
#include <stdlib.h>
int main() {
/* All the variables that needed to be defined */
int *i = malloc(sizeof(int));
int *number = malloc(sizeof(int));
int *failing_count = malloc(sizeof(int));
double *total = malloc(sizeof(double));
double *grade = malloc(sizeof(double));
failing_count = 0;
total = 0;
grade = 0;
/* User is asked to enter the number of grades that are received */
printf("Enter number of grades:\n ");
scanf("%d", number);
/* For Loop is run */
for (*i = 0; i < number; *i++) {
printf("Enter a grade:\n ");
scanf("%lf", grade);
if (*grade < 70) {
failing_count++;
}
*total = *total + *grade;
}
/* Program prints the results */
printf("Average grade is %lf\n", *total / *number);
printf("Number of failing grades is %d\n", failing_count);
return 0;
free(i);
free(number);
free(failing_count);
free(total);
free(grade);
}
total = 0;
。你可能需要使用*total = 0;
。 - chux - Reinstate Monicai
是在自找麻烦 :) - chqrlie