简体   繁体   中英

Accessing elements of a nested structures

when I execute the following code I get an error message for this line scanf("%s",A.(T+i)->CNE)

error message: expected identifier before '(' token|

can I know what is the problem? thanks in advance.

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);
}

(T+i) is not a member of the structure Class , so you cannot use A.(T+i) .

It seems A.(T+i)->CNE should be AT[i].CNE .

Also it is suspicious that the modified A is discarded at returning from the function input . It seems you forgot to write return A; .

The only thing that can be after a . operator is a member name. It cannot be an expression such as (T+i) .

Normally, to access element i of the member T , one would use AT[i] , and then its CNE member would be AT[i].CNE .

Presumably, you have been studying pointer arithmetic and are interested in accessing AT[i] using pointers. In this case, AT + i will give the address of element i of AT . Then (AT + i)->CNE will be the CNE member of that element. (Observe that AT is an array, but, in this expression, it is automatically converted to a pointer to its first element. So AT + i is equivalent to &A.T[0] + i , which says to take the address of AT[0] and advance it by i elements.)

It seems you mean either

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

or

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

That is in the used by you expression

A.(T+i)->CNE

the dot operator expects an identifier instead of an expression.

And your function return nothing though its return type is not void .

The function could be declared and defined for example the following way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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