error:表达式必须在c中具有struct或union类型

时间:2014-10-09 03:47:26

标签: c arrays struct

我一直致力于存储学生姓名和成绩的代码,然后在输入学生姓名时回忆成绩。

这是我的代码:

#include <stdio.h>

#define N 10
#define M 2

struct a
{
     char name[50];
     int grade;
};

int main()
{
    int i;
    int j;
    struct a A[N][M];

    for(i=0;i<N;i++)
    {
         printf("Please Enter Students' Names:/n");
            scanf("%s", &A[i].name);
    }
    for(j=0;j<M;j++)
    {
        printf("Please Enter Students' Grades:/n");
            scanf("%d", &A[j].grade);
    }
    printf("Which Student's Grades Would You Like To View?/n");
        if(scanf("%s", *A[i].name))
        {
            printf("Their Grade Is:%d/n", *A[j].grade);
        }
    return 0;
}

我一直在收到这些错误:

hw2problem2.c(21): error: expression must have struct or union type
                        scanf("%s", &A[i].name);
                                     ^
hw2problem2.c(26): error: expression must have struct or union type
                        scanf("%d", &A[j].grade);
                                     ^
hw2problem2.c(29): error: expression must have struct or union type
                if(scanf("%s", *A[i].name))
                                ^
hw2problem2.c(31): error: expression must have struct or union type
                        printf("Their Grade Is:%d/n", *A[j].grade);
                                                       ^
compilation aborted for hw2problem2.c (code 2)

任何有关错误或程序的帮助都将受到赞赏。 感谢。

3 个答案:

答案 0 :(得分:2)

您将struct a A定义为二维数组,并且仅指定 scanf("%s", &A[i].name);scanf("%d", &A[j].grade);中的一个维度。

您还有其他一些问题,例如scanf("%s", &A[i].name); ...其中 &是不必要的。

答案 1 :(得分:0)

你的程序应该是这样的

for(i=0;i<N;i++)
{
   for(j=0;j<M;j++)
   {
    printf("Please Enter Students' Grades:/n");
        scanf("%d", &A[i][j].grade);
    printf("Please Enter Students' Names:/n");
        scanf("%s", &A[i][j].name);

    }
}

因为,A[i]的类型为struct a*,而不是struct a。它应该是A [i] [j]

逻辑上,您的阵列应该是1-D。因此,循环应该像:

struct a A[N];

for(i=0;i<N;i++)
{
     printf("Please Enter Students' Names:/n");
        scanf("%s", &A[i].name);
}
for(j=0;j<N;j++)
{
    printf("Please Enter Students' Grades:/n");
        scanf("%d", &A[j].grade);
}

如果它是主题,那么它应该是2D并使用嵌套循环,如图所示。

答案 2 :(得分:0)

无需使用2D数组。试试吧..

#include <stdio.h>
#define N 3

struct a
{
 char name[50];
 int grade;
};

int main()
{
int i;
struct a A[N];
    char sname[50];
for(i=0;i<N;i++)
{
     printf("Please Enter Students' Names:/n");
        scanf("%s", A[i].name);
}
for(i=0;i<N;i++)
{
    printf("Please Enter Students' Grades:/n");
        scanf("%d",&A[i].grade);
}

     printf("Which Student's Grades Would You Like To View?/n\n");
     printf("Enter the name...\n");
     scanf("%s",sname);
  for(i=0;i<N;i++)
  {
    if(strcmp(A[i].name,sname)==0)
    {
    printf("%s grade is %d\n",A[i].name,A[i].grade);
    break;
    }
    else
    {
    if(i==N-1)
    printf("No such a name in your list...\n");
    }
  }
 return 0;
 }