i具有以下结构
的函数void calculate_grades(double* total, int n, int* grades){
// n: number of students
// total: scores of students (on a scale of 0-100)
// grades: grades of students (0->A, 1->B, etc.)
int local_grades[n];
for (int i = 0; i < n; i++){
// operations to find the grade
local_grades[i] = result; //calculated grade inside this loop
}
// point grades to local_grades
*grades = test_grades[0];
for (int i = 1; i < n; i++){
test_grades[i] = *grades;
grades++;
printf("%d", *grades);
}
}
我遇到了一个巴士错误:这里10。我要做的是让成绩指向实际成绩,然后能够在其他地方使用它。因此,从本质上讲,当我在循环中的其他地方调用等级时,我希望能够看到实际等级(0或1等(而不是地址?具有这样的功能:
void calculate_grades(double* total, int n, int* grades){
// n: number of students
// total: scores of students (on a scale of 0-100)
// grades: grades of students (0->A, 1->B, etc.)
int local_grades[n];
grades = (int*) calloc(n, sizeof(int));
for (int i = 0; i < n; i++){
// operations to find the grade
grades[i] = result; //calculated grade inside this loop
printf("%d", grades[i]);
}
}
给我函数内部但没有其他地方的正确输入。有帮助吗?
这是我的主要:
int main(){
double scores[10]={34, 24.4, 23.7, 12, 35.4, 64, 2, 45, 88, 11};
int n = 10;
int* grades;
int i;
calculate_grades(scores, n, grades);
printf("MAIN FUNCTION");
for(i = 0; i < n; i++){
printf("%dn", grades[i]);
}
return 0;
}
这是样本输出,我得到
2
3
3
3
2
1
4
2
0
3
MAIN FUNCTION
25
552
1163157343
21592
0
0
0
1
4096
0
c按值传递。您已经更改了功能calculate_grades()
中grades
的本地副本。解决方案是通过地址,然后通过提取该地址进行更改,以更改所需的变量。: -
calculate_grades(scores, n, &grades);
和
void calculate_grades(double* total, int n, int** grades){
int local_grades[n];
*grades = calloc(n, sizeof **grades);
if(!(*grades)){
perror("calloc failure");
exit(EXIT_FAILURE);
}
...
for (int i = 0; i < n; i++){
(*grades)[i] = result; //calculated grade inside this loop
printf("%d", (*grades)[i]);
}
}
和您显示的第一个代码是指出一个指针,其内容不确定 - 这是不确定的行为。
从calculate_scores
删除此行:
grades = (int*) calloc(n, sizeof(int));
然后将int* grades;
更改为main
中的int grades[n];
。
说明:
现在,您将统一指针grades
的值传递给函数calculate_scores
。然后,您为数组分配内存,并覆盖calculate_scores
中本地指针grades
的值(这对main
中的grades
绝对没有影响(。
如果您改为main
方法中的数组,然后将该数组的地址传递给calculate_scores
,就像您已经使用scores
数组一样,该方法可以写入该数组,并且您可以访问main
中的值。