Lecture 18: struct |
The three file cabinets store things of the
|
The file cabinet in the center is used for
|
A struct is a set of variables of mixed type. |
|
A visualization of a struct, namely a motley set of variables. Each variable inside a struct is called a field. Here we have 5 fields: an int (b), a float (f), a char (c), a single array of floats (r) and a double array of doubles (m). |
To declare a struct we do the following
struct {
type1 item1; type2 item2; | typeN itemN; } name; |
As an example, the definition of a struct containing the information of a student might have fields for name, year, and tuition fees paid:
struct {
char name[20]; int year; int propinas; } student; |
name.field |
For example, to assign values to the struct student we can do the following
strcpy(student.name, "Peter Stallinga");
student.year = 2002;
student.propinas = 1;
for the explanation of the function strcpy, see the lecture
on strings.
Another example:
struct {
float x;
float y;
} coordinate;
coordinate.x = 1.0;
coordinate.y = 0.0;
This is not exactly a set of variables of mixed type, so in principle we could also do this with an array:
float coordinate[2];
coordinate[0] = 1.0;
coordinate[1] = 0.0;
but, the first version, with the struct is more logical.
Another example:
struct {
char rua[20];
int numero;
int andar;
char porta;
} address;
strcpy(address.rua, "Rua Santo Antonio");
address.numero = 34;
address.andar = 3;
address.porta = 'E';
printf("%s %d", address.rua, address.numero);
printf("%d %c", address.andar, address.porta);
Rua Santo Antonio 34
3 E
struct {
char name[20]; int year; int propinas; } students[2000]; |
Note the structure of arrays of structs. students
is an array of structs, therefore, students[i]
is one of these structs and if we want to assign something to a field we
use the period and the fieldname, so students[i].year
is an int containing the year of student number i.
Wrong syntax would be students.year[i]
(we could use this if we had a single struct students
containing a field year that is an
array)
Also wrong: students.[i]year,
which doesn't make sense at all. Be careful where you put the dots.
Later we will see that we can much more easily declare variables of
type array of structs (see lecture 19).