简体   繁体   English

当我们的结构是一个数组时,我们如何访问结构的成员?

[英]How can we access members of the structure ,when our struct is an array?

typedef struct grades{
 char s1[DIM];
 char s2[DIM];
 int i;
 float f;

}grades;

void read(grades *s[]);
void write(grades *g[]);
int main() {
    grades v[5];
    read (&v);
    write(&v);
    return 0;
}



void read (grades *s[]){
    printf("enter the name of the student number and point");
    int i;
    for (i=0;i<5;i++){
        scanf("%s %s %d %f",s[i]->s1,s[i]->s2,s[i]->i,s[i]->f );

    }

}

void write(grades *g[]){
    int i;
    for (i=0;i<5;i++){
        printf("%s %s %d %f\n",g[i]->s1,g[i]->s2,(g[i]->i)+5,(g[i]->f)+5 );

    }

in this short program, I want to defien a struct to get students name,surename, number and then grade.在这个简短的程序中,我想定义一个结构来获取学生的姓名、姓名、编号和成绩。 then add 5 grades to their grade and print it.然后在他们的成绩上加上 5 个成绩并打印出来。 when we use array of structs, should we refer to the array, when we use it with pointer?当我们使用结构数组时,当我们使用指针时,我们应该引用数组吗?

You declared an array of structures你声明了一个结构数组

grades v[5];

So in this call所以在这次通话中

write(&v);

the expression &v has the type grades ( * )[5] .表达式&v具有类型grades ( * )[5] This pointer type is not compatible with the functions' parameter type that is implicitly adjusted to grades **g .此指针类型与隐式调整为grades **g的函数参数类型不兼容。

You need to declare the functions like你需要声明像这样的函数

void read(grades *s, size_t n);
void write( const grades *g, size_t n);

and to call the functions like并调用函数

read( v, 5 );
write( v, 5 );

This call of scanf这个 scanf 调用

scanf("%s %s %d %f",s[i]->s1,s[i]->s2, s[i]->i, s[i]->f );    

shall be rewritten at least like至少应该重写

scanf("%s %s %d %f",s[i].s1,s[i].s2, &s[i].i, &s[i].f );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM