使用指针

时间:2018-02-22 16:43:32

标签: 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];

   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。我要做的是将成绩指向计算出的实际成绩,然后才能在其他地方使用。所以基本上当我在一个循环中的其他地方调用成绩[i]时,我希望能够看到实际成绩(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("%d\n", 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

2 个答案:

答案 0 :(得分:2)

C是按值传递的。您已对函数grades中的calculate_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]);
   }
}

您展示的第一个代码是取消引用内容不确定的指针 - 这是未定义的行为。

答案 1 :(得分:1)

calculate_scores

中删除此行
grades = (int*) calloc(n, sizeof(int));

然后在int* grades;中将int grades[n];更改为main

<强>解释

现在您将单位化指针grades的值传递给函数calculate_scores。然后为数组分配内存,并覆盖grades内的本地指针calculate_scores的值(这对grades中的main完全没有影响。)

如果您在main方法中创建数组并将该数组的地址传递给calculate_scores,就像您已经使用scores数组一样,该方法可以写入该数组数组,您可以访问main中的值。