I’m studying C++ from Schildt’s book and don’t quite understand what does he mean under third structure; Can somebody explain this ->
To access a specific structure within
an array of structures, you must index
the structure name. For example, to
display the on_hand member of the
third structure, you would write
cout << invtry[2].on_hand;
Some code:
struct type{
char item[40];
double cost;
double retail;
int on_hand;
int lead_time;
}invtry[SIZE];
The third structure in an array of structures is the one placed in the third position in the array, i.e., the one with index 2.
In your (ugly) code,
invtryis declared as an array (of sizeSIZE) of structures of typetype. Henceinvtry[0]is the first element,invtry[1]the second, andinvtry[2]the third – assuming, of course,SIZE >= 3.Normally, you would write:
This is synonymous to what you wrote, except for the definition of
SIZEof course. But it leads to less confusion – in one part you say what atype(terrible name for the struct!) is – in other words, you define the typetype. Later, you create an array of structs of typetype, calledinvtry.Doing this in the same line, as the author did, is simply awful – to my eyes.
Now you have an array of 500 structs. If “type” was “Product”, you would have an array representing 500 products. Each one with its item, cost, retail, etc.
To access the third struct in the array, write
invtry[2]. to access its particularon_handfield, writeinvtry[2].on_hand. This has nothing to do with the specific position ofon_handin the layout of the defined type.If you want the lead_time of the third structure, first access the third structure and then its
lead_timemember:invtry[2].lead_time.Of course since type does not have a default (parameterless) constructor, the 500 products are uninitialized – you have garbage in them. But that is your problem.