什么是“请求会员' *******'在不是结构或联合的东西中“是什么意思?

时间:2013-08-23 21:18:29

标签: c++ c struct

这个错误的含义是否容易解释?

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


struct student {
        char Surname[30];
        char Name[30];
        int Age;
        char Address[10];

};

int main(){
     int i;
     char temp1;
     char temp2;
     int temp3;;
     char temp4;
     struct student x[2];
     for(i=1; i<3; i++){
              struct student x[i];
             printf(" Surname of Student %s:", i);
             scanf("%s",&temp1);
             printf(" Other names of Student %s:", i);
             scanf("%s",&temp2);
             printf(" Age of Student %s:", i);
             scanf("%s",&temp2);
             printf(" Address of Student %s:", i);
             scanf("%s",&temp3);
             strcpy(x->Surname,&temp1);
             strcpy(x->Name,&temp2);
             //x[i].Surname=temp1;
             //x[i].Name=temp2;
             x[i].Age=temp3;
             //x[i].Address=temp4;
             strcpy(x->Address,&temp4);

             }
     int temp;
     if (x[1].Age > x[2].Age){
                     temp = 1;
                     printf(x.Surname[temp]);
                     printf(x.Name[temp]);
                     printf(x.Age[temp]);
                     printf(x.Address[temp]);
                  }
     else if(x[1].Age < x[2].Age){
                     temp = 2;
                     printf(x.Surname[temp]);
                     printf(x.Name[temp]);
                     printf(x.Age[temp]);
                     printf(x.Address[temp]);
                  }
     else{
                     printf(x.Surname[1]);
                     printf(x.Name[1]);
                     printf(x.Age[1]);
                     printf(x.Address[1]);

                     printf(x.Surname[2]);
                     printf(x.Name[2]);
                     printf(x.Age[2]);
                     printf(x.Address[2]);

                      }

     return 0;









};

我收到成员`Surname'的错误请求,而不是结构或联合......实际上它适用于所有打印行...有人可以帮助我吗?我是C编程的新手....

2 个答案:

答案 0 :(得分:3)

更改

                 printf(x.Surname[temp]);

                 printf(x[temp].Surname);

x是指针还是数组,你不能从中获取结构成员。

您的代码中还有其他奇怪之处。特别是:

 struct student x[2]; // this array never receives data because the other x shadows it
 for(i=1; i<3; i++){
          struct student x[i]; // this declaration shadows the earlier declaration

我的猜测是你打算做更像

的事情
 struct student x[2];
 for(i=0; i<2; i++){
          struct student *ptr = &x[i];

然后你对箭头操作符->的使用也会更有意义。

此外,这是一个问题:

                 printf(x.Age[temp]);

即使我们修改了

的struct访问权限
                 printf(x[temp].Age);

你不能将整数传递给printf。字符串可以用作格式字符串,但对于整数,您必须在字符串中给出格式规范。

                 printf("%d", x[temp].Age);

答案 1 :(得分:1)

好的,这段代码比廉价汽车旅馆有更多的错误。

这是一个明显的错误:

scanf("%s",&temp1);

“%s”格式字符串需要一个指向字符数组的指针,它可以放置字符串,包括空字符。但是您已经将temp1声明为:char temp1,这是一个单个字符。除非你的名字长度为0,否则你会遇到问题。更好地定义它:

char temp1[30];

或直接写入您的结构成员并跳过strcpy

scanf("%s", x[i].Surname);

然后你有至少29个字符的空间。但如果用户希望输入超过29个字符,则仍然存在问题。