I have been dealing with this problem for quite some time, I've been assigned to develop a program that can store products' information within structures (the number of products is undefined). I thought I should use an array of structures, but I don't know how to declare it properly.
This is what I thought would work:
1 2 3 4 5 6
struct product {
string name;
string in_stock;
float sale_cost;
int id; }
prod [n]; //n being the undefined number of products the user will register/delete/modify
I already saw an example of array of structures, but it uses a defined number.
The program should not deal with dynamic memory management due to being programmed in very basic topics, anyways, so if I just use a big enough array like:
1 2 3 4 5 6 7 8
#define n 500
struct product {
string name;
string in_stock;
float sale_cost;
int id; }
prod [n];
how can I access it properly in different functions (without using pointers)?
The in_stock variable looks (by its name) as though it should be a bool and not a string?
I would suggest that you add a default constructor to your struct so that you initially set the member variables to a default value so that you can tell when you have reached the end of the array that has been used, say id = -1, as you have chosen not to use vectors or pointers.
Oh, my bad, I should have specified what the variables mean:
1 2 3 4 5 6 7 8 9
#define n 500
struct product {
string name; //name of the item
int in_stock; //number of the item in stock
float sale_cost; //cost of the item
int id; //Identification number of the item
}
prod [n];
(Changed the in_stock type of data to a proper one, though that ajh32 says looks like it might fit in the program later)
So my problem with the syntaxis of the structure is solved, thanks alot. But the other problem, about how to access the data from different functions, remains. Can you help with some examples?
My bad, again. Yes, I am declaring the prod as global (I should learn to include all those little details before hand).
I see, so declaring it as global lets me access the data from any function? Sorry if it turns out obvious, but I got a misconception about variable usage during my courses.
I'll take note about that, I did consider using classes, but is it kind of forbidden for me to use them this semester, as they want us to just use some specific c++ topics. Anyhow, I will keep on mind using classes next time, thanks!