Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用指针更新C中的数组_C_Arrays_Pointers - Fatal编程技术网

用指针更新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));