I\'m having trouble passing an array of structs to a function in C.
I\'ve created the struct like this in main:
int main()
{
struct Items
{
Define struct Items outside of main. When passing an array to a function in C, you should also pass in the length of the array, since there's no way of the function knowing how many elements are in that array (unless it's guaranteed to be a fixed value).
As Salvatore mentioned, you also have to declare (not necessarily define) any structs, functions, etc. before you can use them. You'd usually have your structs and function prototypes in a header file in a larger project.
The below is a working modification of your example:
#include
struct Items
{
char code[10];
char description[30];
int stock;
};
void ReadFile(struct Items items[], size_t len)
{
/* Do the reading... eg. */
items[0].stock = 10;
}
int main(void)
{
struct Items MyItems[10];
ReadFile(MyItems, sizeof(MyItems) / sizeof(*MyItems));
return 0;
}