2017-09-24 111 views
0

我已經在我的代碼struct Stdinfo中聲明瞭一個結構,其中包含學生的姓名和分數。訪問結構非數組元素

#include <stdio.h> 
     struct Stdinfo{ 
     char name[30]; 
     int score; 
    }; 

然後我創建的struct Stdinfo CreatStruct()名稱的功能,這裏面的結構。還應該提及我的結構變量是數組。結構完成後,我將其地址存儲在指針struct Stdinfo *structPtr中。然後,我通過了地址下面的功能:

void FindAverage(struct Stdinfo *structPtr ,size_t stdnum){ 

     int j; 

     for(j = 1 ; j < stdnum ; j++) 
      { 
       //Error line 
       if((structPtr[j] -> score) < (structPtr[j] -> score)) { 

        /*... 
        * 
        * ? 
        * 
        */ 


        } 
      } 

      ////printf(The answer); 
    } 

我的整個代碼:

#include <stdio.h> 
#include <string.h> 

struct Stdinfo{ 
     char name[30]; 
     int score; 
    }; 

struct Stdinfo CreatStruct(); 
void FindAverage(struct Stdinfo * ,size_t); 

int main(void) 
{ 
    //Number of students ~stdnum 
    size_t stdnum; 
    int i; 
    puts("Input numbers of student(s) :") ; 
    scanf("%Iu" ,&stdnum); 

    struct Stdinfo student[stdnum] ; 

    //Filling array of structure 
    for(i=0 ; i < stdnum ; i++) 
    { 
     student[i] = CreatStruct() ; 
    } 

    struct Stdinfo *structPtr; 
    structPtr= student; 
    FindAverage(structPtr ,stdnum); 

    return 0; 
} 

struct Stdinfo CreatStruct() { 

    struct Stdinfo student; 

    getchar(); // Consume newline from previous input 

    printf("Input the name of the student : ") ; 
    fgets(student.name , sizeof (student.name) , stdin); 
    // remove trailing newline from 'fgets()' 
    student.name[strcspn(student.name, "\n")] = 0; 

    puts("Input his(her) score:") ; 
    scanf("%i" ,&student.score) ; 

    return student ; 
} 

void FindAverage(struct Stdinfo *structPtr ,size_t stdnum){ 

    int j; 

    for(j = 1 ; j < stdnum ; j++) 
     { 
      if((structPtr[j] -> score) < (structPtr[j] -> score)) { //Error line 

       /*... 
       * 
       * ? 
       * 
       */ 


       } 
     } 

     ////printf(The answer); 
} 

目標是打印的最大比分,但我不知道怎麼去訪問它。

我很感謝有人幫我解決這個問題。

+0

你在'錯誤行'中遇到了哪個錯誤? – MondKin

+1

我不明白爲什麼'if(structPtr [j] - > score score)',刪除了不必要的空格和括號。 –

+0

@ MondKin- if((structPtr [j] - > score)<(structPtr [j] - > score)) –

回答

0

更換structPtr[j] ->structPtr[j].

您遇到的錯誤是因爲你提領該陣列的兩倍。該->操作是(*x).只是語法糖和[N]*(x + N)只是語法糖所以你的情況,structPtr[j]->轉化爲**(structPtr + j),才能訪問你需要取消引用它只有一次這樣的陣列時:*(structPtr + j)