2014-11-15 451 views
-2
#include <stdio.h> 
    #include <stdlib.h> 

    float average_score(int** array_score) 
    { 
     int i, j; 
     int sum = 0; 

     for(i = 0; i < 4; i++) 
      { 
       for(j = 0; j < 4; j++) 
        { 
         sum += *(*(array_score + i) + j); 
        } 
      } 

     printf("sum/16 = %d\n", sum/16); 
     return (float) sum/16; 
    } 

    int lowest_score(int** array_score) 
    { 
     int i, j; 
     int temp = **array_score; 

     for(i = 0; i < 4; i++) 
      { 
       for(j = 0; j < 4; j++) 
        { 
         if(temp > *(*(array_score + i) + j)) 
    //------ 
          temp = *(*(array_score + i) + j); 
         printf("%d ",*(*(array_score + i) + j)); 
        } 
//-- 
       printf("\n"); 
      } 

     printf("low_score = %d\n", temp); 
     return temp; 
    } 

    int main(int argc, char** argv) 
    { 
     int **array_score = NULL; 

     int i = 0; 
     int j = 0; 

     //Create a two-dimensional array 
     array_score = (int **) malloc(4 * sizeof(int *)); 
     for(i = 0; i <= 4; i++) 
      array_score[i] = (int *)malloc(4 * sizeof(int)); 
//--  
     for(i = 0; i < 4; i++) 
      { 
       printf("Please enter the student_%d four grades, (separated with a space)\n", i+1); 
       int ret = scanf("%d %d %d %d", (*(array_score + i) + 0), (*(array_score + i) + 1), 
           (*(array_score + i) + 2), (*(array_score + i) + 3)); 
       fflush(stdin); 
       if(4 != ret) 
        i--; 
      } 

     //There is something wrong with the function return value 
     float ave_score = average_score(array_score); 
//-- 
     int low_score = lowest_score(array_score); 

     //The output 
     printf("average score: %d\n lowest score: %d\n", ave_score, low_score); 

     return 0; 
    } 
+3

而你的問題是? – Rizier123

+0

你期望得到什麼?你究竟得到了什麼? – davidc

+0

我想要子函數返回值,但它給了我一個不好的值 – wuxiudong

回答

1

這4個指針分配空間,然後將寫入5,由於i取值爲0,1,2,3和4:

array_score = (int **) malloc(4 * sizeof(int *)); 
    for(i = 0; i <= 4; i++) 
     array_score[i] = (int *)malloc(4 * sizeof(int)); 

注意,在C你不應該從malloc投下回報。在Stackoverflow上有一個答案告訴所有細節爲什麼這沒有幫助。