Type Declaration
When a new structure is created, we are actually declaring a new data type. They are called structure type.
Structure Type
Syntax
struct | |
---|---|
1 2 3 4 5 6 |
|
Note that a type is NOT a variable.
Remember, a variable has 4 attributes: name, type, address and value.
By declaring a structure type using typedef
, we are basically saying that there is this new type called <struct name>
.
In particular, do note the following major differences:
- A type needs to be defined before we can declare variable of that type.
- No memory is allocated to a type.
- Memory will only be allocated when a variable of that type is declared.
Structures
account_t | |
---|---|
1 2 3 4 |
|
result_t | |
---|---|
1 2 3 4 5 |
|
As a good practice, you should put any type declaration before function prototypes so that it can be used by the function prototype1.
However, it should be after preprocessor directives so that you can use other types declared in a library if you are using #include
.
Additionally, you should also name the structure with a suffix _t
at the end to indicate that this is a new type.
C Program Template with Structure
Template | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Array of Structures
Now that we have managed to create a structure for student results, we can combine this structure with array to create an array of structures. This will be particularly useful at the end of the semester when we have to submit the results of all students.
Since a structure creates a type, we can then create an array this type.
Array of Student Results | |
---|---|
1 |
|
Each of the element in the array variable all_results
is of type result_t
.
-
Remember, C compiler is one-pass compiler. If the compiler have never seen the type before, it cannot be used. ↩