Working with Structures
Structures represent user-defined types. A set of rules regarding the application of structures is strictly defined.
Assignment
Variables of the same structured type may be assigned one to another by means of simple assignment operator (=
). This will copy the entire contents of the variable to destination, regardless of the inner complexity of a given structure.
Note that two variables are of the same structured type only if they are both defined by the same instruction or using the same type identifier. For example:
/* a and b are of the same type: */ struct {int m1, m2;} a, b; /* But c and d are _not_ of the same type although their structure descriptions are identical: */ struct {int m1, m2;} c; struct {int m1, m2;} d;
Size of Structure
The size of the structure in memory can be retrieved by means of the operator sizeof
.
It is not necessary that the size of the structure is equal to the sum of its members’ sizes. It is often greater due to certain limitations of memory storage.
Structures and Functions
A function can return a structure type or a pointer to a structure type:
mystruct func1(void); /* func1() returns a structure */ mystruct *func2(void); /* func2() returns pointer to structure */
A structure can be passed as an argument to a function in the following ways:
void func1(mystruct s;); /* directly */ void func2(mystruct *sptr;); /* via a pointer */
What do you think about this topic ? Send us feedback!