【问题标题】:Accessing elements of a nested structures访问嵌套结构的元素
【发布时间】:2021-04-03 13:10:45
【问题描述】:

当我执行以下代码时,我会收到一条错误消息,此行 scanf("%s",A.(T+i)->CNE)

错误信息:expected identifier before '(' token|

我能知道是什么问题吗?提前致谢。

typedef struct date
{
    int day;
    int month;
    int year;
}date;
typedef struct Student
{
    char CNE[10];
    char FirstName[30];
    char LastName[30];
    date BD;
    float Grades[6];
}Student;
typedef struct Class
{
    Student T[1500];
    int dim;
}Class;
Class input(Class A)
{
    int i=A.dim;
    printf("Enter the student CNE : ");
    scanf("%s",A.(T+i)->CNE);
}

【问题讨论】:

    标签: c data-structures struct compiler-errors member-access


    【解决方案1】:

    . 运算符后面唯一可以是成员名称。不能是(T+i)等表达式。

    通常,要访问成员T 的元素i,将使用A.T[i],然后其CNE 成员将是A.T[i].CNE

    想必您一直在研究指针算法,并对使用指针访问A.T[i] 感兴趣。在这种情况下,A.T + i 将给出A.T 的元素i 的地址。然后(A.T + i)->CNE 将成为该元素的CNE 成员。 (注意A.T 是一个数组,但是,在这个表达式中,它会自动转换为指向其第一个元素的指针。所以A.T + i 等价于&A.T[0] + i,表示取A.T[0] 的地址并且将其推进i 元素。)

    【讨论】:

      【解决方案2】:

      (T+i) 不是结构Class 的成员,因此不能使用A.(T+i)

      看来A.(T+i)->CNE 应该是A.T[i].CNE

      同样值得怀疑的是,修改后的A 在从函数input 返回时被丢弃。你好像忘了写return A;

      【讨论】:

        【解决方案3】:

        看来你的意思是要么

        scanf("%s",A.T[i].CNE);
        

        scanf("%s", ( A.T + i )->CNE );
        

        那是在你使用的表达式中

        A.(T+i)->CNE
        

        点运算符需要一个标识符而不是表达式。

        尽管返回类型不是void,但您的函数什么也不返回。

        函数可以通过以下方式声明和定义,例如

        void input(Class *A)
        {
            int i = A->dim;
            printf("Enter the student CNE : ");
            scanf( "%s", ( A->T + i )->CNE );
        }
        

        【讨论】:

          最近更新 更多