Knowing how structures work makes using them a lot easier. We know that C is actually very simple minded about the way that it does things, this includes how it handles structures.
When C is given a struct definition it goes Aha! Here comes a structure. I will work out how much memory it needs and remember whereabouts in this chunk of memory each member starts. This means that for our bank example :
The first 30 locations of the structure hold the name:
char name [30]
The next 60 locations hold the address:
char address [60]
Next comes space for the account number:
int account
.. and so on. When you declare a variable of this structured type C makes a variable of the correct size. On the right you can see how the various items are arranged down memory to form the structure.
When you then do something like
OnlyOne.account = 99 ;
C says, "I remember that the account value is stored after the 90 characters of the name and address members", and puts the value in the correct place.
If you have an array of structured variables, C just grabs a block of memory which is :
size of array * size of structure
- in size and then fills in the members of each structure as it goes.
This means that, if you know how much memory int, float and char variables take up, you can work out how much memory any given structure needs. However, since C has already done this for you, it seems a little silly to have to do it manually. C provides a facility called sizeof (item). This returns the number of locations which the item takes up in memory.
Information grouped together in a struct