gpt4 book ai didi

c - C语言中指针的使用

转载 作者:行者123 更新时间:2023-12-04 11:51:43 25 4
gpt4 key购买 nike

当我运行此代码时,它返回 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);
}

最佳答案

使用 *在任何地方你想使用所指向的值而不是指针。

改变:

        failing_count = 0; 
total = 0;
grade = 0;

到:
        *failing_count = 0; 
*total = 0;
*grade = 0;

改变:
        for(*i = 0; i<number; *i++){ 

到:
        for(*i = 0; *i<*number; (*i)++){ 

改变:
                        failing_count++; 

到:
                        (*failing_count)++; 

改变:
        printf("Number of failing grades is %d\n", failing_count); 

到:
        printf("Number of failing grades is %d\n", *failing_count); 

在:
        return 0; 

free(i);
free(number);
free(failing_count);
free(total);
free(grade);
return 后面的语句永远不会被执行。移动 return最后。

关于c - C语言中指针的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60215746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com