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
{
char code[10];
char description[30];
int stock;
};
struct Items MyItems[10];
}
I then access it like: MyItems[0].stock = 10;
etc.
I want to pass it to a function like so:
ReadFile(MyItems);
The function should read the array, and be able to edit it. Then I should be able to access the same array from other functions.
I've tried heaps of declarations but none of them work. e.g.
void ReadFile(struct Items[10])
I've had a look around for other questions, but the thing is they're all done different, with typedefs and asterisks. My teacher hasn't taught us pointers yet, so I'd like to do it with what I know.
Any ideas? :S
EDIT: Salvatore's answer is working after I fixed my prototype to:
void ReadFile(struct Items[10]);
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.
struct Items
{
char code[10];
char description[30];
int stock;
};
void ReadFile(struct Items items[10])
{
...
}
void xxx()
{
struct Items MyItems[10];
ReadFile(MyItems);
}
This in my compiler works well. What compiler are you using? What error you got?
Remember to declare your struct before your functions or it will never work.
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 <stdio.h>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With