I am learning some C, and I have the following code, basically want I would like to do is to increase the size of people
array in the for loop, but currently I receive an error.
Could you please provide me a fix to my script with a brief explanation?
#include <stdio.h>
struct Person {
int id;
};
struct State {
struct Person people[0];
};
int main() {
printf("Hello, world!");
struct State state = {};
for(int i = 0; i < 10; i) {
struct Person person = {};
person.id = i;
state->people[i] = person;
}
return 0;
Error I receive:
clang-7 -pthread -lm -o main main.c
main.c:19:12: error: member reference type 'struct State' is not
a pointer; did you mean to use '.'?
state->people[i] = person;
~~~~~^~
.
1 error generated.
exit status 1
CodePudding user response:
The error is pretty self-explanatory, given that you know what ->
is used for: it is used when the struct (its left operand) is a pointer. It's equivalent to (*pointer_to_struct).
. It does not matter what type the right operand of ->
got.
You have no pointers to structs in your code so you can't use ->
.
Also struct State state = {}
is invalid C, an initializer list cannot be empty. You need to set at least one element, so for example you can do {0}
and that will set everything in the struct to zero/null.