Data
Structure |
Structured Data Objects (Structs)
Tutorial 7.20
How many bytes of storage do we need for a struct ?????
First, keep in mind that a struct is an array with a
fixed number of contiguous storage elements, but unlike an array, the struct elements do not need to be all of the same data type.
Lets say we want to make a list of Bank customers. We want to track the customer’s name, their
account number, the date the account was opened, the balance of the account,
and the account officer.
We need to determine how much space will be needed
for each type of data.
Fields
Requested |
Date Type |
Customer Name |
String (allow for 30
characters) |
Account Number |
Integer (int) |
Date Account Opened |
String (allow for 10
characters - mm/dd/yyy) |
Account Balance |
Real (float) |
Account Officer Number |
Interger (int) |
|
|
So our struct will contain the following data:
Element |
Bytes |
char customer_name[31]; |
31 |
int account_number; |
2 |
char date_opened[11]; |
11 |
float balance; |
4 |
int officer_num; |
2 |
Total bytes needed: |
50 |
We need 50 bytes of contiguous RAM storage for our data type struct customer.
Our struct would look like
this:
Struct customer
{ char customer_name[31];
int account_number;
char date_opened[11];
float balance;
int officer_num;};
Consider the Questions and
answers below:
Question:
If there are only 10 spaces, or bytes, needed
for date_opened, why do we need 11 bytes?
Answer:
Because we need one
additional bye for the ‘\0’, which comes after a character string.
Question:
Is a struct considered a data type, the
same as an integer, a float, a character, or a pointer?
Answer:
Yes, when we set up a struct, such our
struct customer, we are creating a new data type.
Question:
Once we store a struct, can we locate
it later?
Answer:
As with all data types, a struct has a
base address, since it has a fixed number of elements, if we know the base
address, how many
elements are in the stuct and their size, we can locate any portion of the
struct that we wish to see.