简体   繁体   中英

How to access a specific structure in array in C?

I have this:

typedef struct{
    field_1;
    field 2;
    .....
}student;

typedef struct{
    student record[100];
    int counter;
}List;

Then I want to add the information for each 'student', for example:

List *p;
gets(p->list[index]->field_1);

but when I compiled the code it threw this:

[Error] base operand of '->' has non-pointer type 'student'

So why can't I point to 'list' and way to access a specific 'record' in 'list'?

The list itself, p , is a pointer, but the value record[100] is not. You would use the -> operator to access values from p then the . operator to access values from the member records .

When you write

  `p->record[index]->field_1`

it is expanded as (*p).(*record[index]).field_1

  record[index]` 

itself returns a value so there is no sense in adding * operator before that. But you can use

p->(record+index)->field_1

Adding code snippet that may help you to read/write the values to the records. Free the pointer to a struct when you're done.

typedef struct{
int age;
int marks;
}student;

typedef struct{
student record[100];
int counter;
}List;

int main()
{ 
    List *p = (List*)malloc(sizeof(List));

    p->record[0].age = 15;
    p->record[0].marks = 50;
    p->counter = 1;
    free(p);
    return 0;
}

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