I've been tearing my hair out over this for quite a while now. What I'm trying to do is populate the struct array from within a function but I cannot figure out how to do it. Everything I've tried throws up a syntax error.

Ideally the data should be entered from the user using scanf (hence the int num within the function for a for loop), but for the sake of clarity and because this is all new material to me, I'm trying initially to fill up the struct directly from code.

I've searched all over the web for a solution, but found nothing. I've come to the conclusion that I'm approaching this entirely from the wrong angle, or there's a tiny error somewhere.

Any help would be appreciated.

typedef struct
{
	char title[40];
	char author[40];
	int edition;
	float retail_price;
} book ;

void populateStock(book stock[],int num);

void main()
{
	book stock[10];
	populateStock(stock,5);
}

void populateStock(book stock[],int num)
{
	stock[0]={"example title1","example author1",1,5.80};
        stock[1]={"example title2","example author2",4,7.20};
        //And so on...//
}

Struct (or arrays of structs) can only be populated in the form you show at declaration. So to do what you want you need to do one of the following:

strncpy (stock[0].title, "example title1", 40);
strncpy (stock[0].author, "example author1", 40);
stock[0].edition = 1;
stock[0].retail_price 5.80;

or

book stock[10] = {
   {"example title1", "example author1", 1, 5.80},
   {"example title2", "example author2", 4, 7.20},
   ...

Thanks for your help. I think I tried something similar to that earlier but it threw up an error.

Your first method works fine, but if I try your second method I get:
error C2082: redefinition of formal parameter 'stock'

Is there a way around that?

Sorry, I should have specified.
The first method would happen within the function call. The second, the one you are getting an error with, should happen in main where you declare the book array first.
Also, you should only do one or the other.

Ah, it all makes sense now. It's working perfectly.
Thanks so much for your help.

You example and one of L7Sqr's example violates a very important part of your task, namely:

Ideally the data should be entered from the user using scanf (hence the int num within the function for a for loop)

Why try to load the data in a different way? Just concentrate on what you actually need to accomplish -- user input. Use his 1st example with your inputs.

Chances are you will still have problems using scanf() , but reading this series will help you fix them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.