2017-09-24 115 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)