Home > Blockchain >  expected expression before '{' token in the nested struct
expected expression before '{' token in the nested struct

Time:08-19

I need your solution and explanation about this issue. I tried to declare array struct of Books inside the Bookstore1 struct. Then, I got the error "expected expression before '{' token" at the 17th line.

#include <stdio.h>
#include <string.h>

struct book{
    char name[20];
    int price;
    double rating;
};

struct bookStore{
    char nameStore[20];
    struct book Books[2];
};

int main(){
    struct bookStore Bookstore1;
    Bookstore1.Books = {{"Javascript",300,4.2},{"Algorithm",200,2.5}};
    printf("%d",Bookstore1.Books[0].price);
    return 0;    
}

CodePudding user response:

You can't assign to an array, and you can't use initialization lists in assignments (although you can use compound literals, which are similar).

You can assign to individual array elements using compound literals:

Bookstore1.Books[0] = (book){"Javascript",300,4.2};
Bookstore1.Books[1] = (book){"Algorithm",200,2.5};

or you can do it when initializing the array;

struct bookStore Bookstore1 = {
    .Books = {{"Javascript",300,4.2},{"Algorithm",200,2.5}}
};

Note that using a fixed-size array for a Bookstore structure is quite limiting (how many bookstores would only have 2 books?). You would be better off using a pointer, and then use dynamic memory allocation to create an array of as many books as you need. You can then reallocate it if more books are added to the store.

  • Related