Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

expected expression before '{' token in the nested struct

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading