0

这个错误的含义有一个简单的解释吗?

#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;









};

我在不是结构或联合的情况下收到对成员“姓氏”的错误请求...实际上是针对所有打印行...有人可以帮我解决这个问题吗?我是 C 编程新手....

4

2 回答 2

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);
于 2013-08-23T21:21:17.700 回答
1

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

一个明显的错误是:

scanf("%s",&temp1);

"%s" 格式字符串需要一个指向字符数组的指针,它可以在其中放置字符串,包括空字符。但是您已经像这样声明了 temp1: char temp1,它是单个字符。除非您的名称长度为 0,否则您将遇到问题。最好像这样定义它:

char temp1[30];

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

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

那么您有最多 29 个字符的空间。但是如果用户想要输入超过 29 个字符,您仍然会遇到问题。

于 2013-08-23T23:44:21.580 回答