Node:Using structures, Next:Arrays of structures, Previous:Structure declarations, Up:struct
Using structures
Structures are extremely powerful data types. Not only can you pass a whole structure as a parameter to a function, or return one as a value from a function. You can even assign one structure to another.
You can get and set the values of the members of a structure with the
.
dot character. This is called the member operator. The
general form of a member reference is:
structure_name.member_name
In the following example, the year 1852 is assigned to the
year_of_birth
member of the structure variable person1
, of
type struct personal_data
. Similarly, month 5 is assigned to the
month_of_birth
member, and day 4 is assigned to the
day_of_birth
member.
struct personal_data person1; person1.year_of_birth = 1852; person1.month_of_birth = 5; person1.day_of_birth = 4;
Besides the dot operator, C also provides a special ->
member
operator for use in conjunction with pointers, because pointers and
structures are used together so often. (See Pointers to structures.)
Structures are easy to use For example, you can assign one structure to
another structure of the same type (unlike strings, for example, which
must use the string library routine strcpy
). Here is an example
of assigning one structure to another:
struct personal_data person1, person2; person2 = person1;
The members of the person2
variable now contain all the data of the members
of the person1
variable.
Structures are passed as parameters in the usual way:
my_structure_fn (person2);
You would declare such a function thus:
void my_structure_fn (struct personal_data some_struct) { }
Note that in order to declare this function, the struct personal_data
type must be declared globally.
Finally, a function that returns a structure variable would be declared thusly:
struct personal_data structure_returning_fn () { struct personal_data random_person; return random_person; }
Of course, random_person
is a good name for the variable returned
by this bare-bones function, because without unless one writes code to
initialize it, it can only be filled with garbage values.