0

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'?

2
  • 2
    Use the . operator instead of -> (the second one).. Commented Jan 16, 2017 at 18:15
  • Or complentarty create an array of pointers to student. Commented Jan 16, 2017 at 18:16

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. I was asking about using the malloc() function. But will calling sizeof(List) create unused counter variables?
No it will not. It will allocate memory of 4 bytes for counter variable only.
1

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.

1 Comment

Then can I use malloc() function instead of giving a fixed number of records? Will there be any problems?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.