用指针更新C中的数组
我有一个函数,它的结构如下用指针更新C中的数组,c,arrays,pointers,C,Arrays,Pointers,我有一个函数,它的结构如下 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]; fo
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);
}
}
C是传递值。您已在函数
calculate_grades()
中更改了grades
的本地副本。解决方案是传递地址,然后通过取消引用来更改所需的变量:-
calculate_grades(scores, n, &grades);
及
void calculate\u等级(双*总计、整数n、整数**等级){
国际本地大学成绩[n];
*等级=calloc(n,尺寸**等级);
如果(!(*等级)){
perror(“calloc故障”);
退出(退出失败);
}
...
对于(int i=0;i
您显示的第一个代码是取消对内容不确定的指针的引用,这是未定义的行为。从
计算分数中删除这一行:
grades = (int*) calloc(n, sizeof(int));
然后更改int*等级代码>至内部等级[n]代码>在main
中
说明:
现在,您正在将单位化指针grades
的值传递给函数calculate\u scores
。然后为数组分配内存,并覆盖calculate\u scores
中本地指针grades
的值(这对main
中的grades
绝对没有影响)
如果改为在main
方法中创建数组,并将该数组的地址传递给calculate\u scores
,就像您已经使用scores
数组一样,该方法可以写入该数组,您可以访问main
Post中的值…………我针对我遇到的实际问题发布了足够的信息,不想用不相关的行重载Post。您希望我添加什么样的澄清?如何调用函数?参数类型是什么?etc阅读链接段落。提示:grades
指向哪里?我的错,对不起!我做了一些修改,希望能让它更清晰。非常感谢你的解释!非常感谢。现在我明白你所说的未定义的行为是什么意思了。
2
3
3
3
2
1
4
2
0
3
MAIN FUNCTION
25
552
1163157343
21592
0
0
0
1
4096
0
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]);
}
}
grades = (int*) calloc(n, sizeof(int));