cdata-structuresstructcompiler-errorsmember-access

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

Solution

  • 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 A.T[i], and then its CNE member would be A.T[i].CNE.

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