C++ Arrays of Structure access
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, invtry
is declared as an array (of size SIZE
) of structures of type type
. Hence invtry[0]
is the first element, invtry[1]
the second, and invtry[2]
the third - assuming, of course, SIZE >= 3
.
Normally, you would write:
struct type{
char item[40];
double cost;
double retail;
int on_hand;
int lead_time;
};
const int SIZE = 500;
type invtry[SIZE];
This is synonymous to what you wrote, except for the definition of SIZE
of course. But it leads to less confusion - in one part you say what a type
(terrible name for the struct!) is - in other words, you define the type type
. Later, you create an array of structs of type type
, called invtry
.
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 particular on_hand
field, write invtry[2].on_hand
. This has nothing to do with the specific position of on_hand
in 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_time
member: 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.
Try substituting 'array item' for 'structure'.
So to access the 3rd item in the invtry array (which is an array of structs), you'd use invtry[2] (2 rather than 3 as the index is 0-based), followed by the member variable you wish to read...
i.e. invtry[2].on_hand gets the value held in 'on_hand' of the 3rd struct in the array 'invtry'
You shouldn't try to learn from a Schildt book. They are seriously flawed. Much information in it is seriously outdated or downright wrong. The code is written in a ugly and bad style with many C-isms in it. see ACCU Book reviews for a more detailed review of his books.
Try "Accelerated C++" by Koenig and Moo or "Programming Principles and Practice using C++" by Stroustrup for good beginners guides.
精彩评论