Skip to content

Structs

frankpfenning edited this page Aug 18, 2011 · 7 revisions

A struct aggregates data of different type. Structs must be declared so that the compiler can check that its components are used at the correct types. For example,

struct person {
  int id;
  string name;
  int age;
};

declares struct person to a type whose values are tuples consisting of an id (of type int), a name (represented as a string), and an age (again, an int). id, name, and age are called the fields of the struct.

The C0 programming language does not provide any explicit notation for values of type struct s. Such values are large and cannot be held directly in a variable. Instead, they must be in allocated memory. For example

--> struct person p;  /* error */
--> struct person * p;  /* ok */
--> p = alloc(struct person);  /* ok */
-->

If we have a pointer to a struct, we can read its value using the p -> f notation, where p is a pointer to a struct s and f is a valid field for a struct s.

--> p->id;
--> p->name;
--> p->age;

We see that each field has been initialized to a default value of the given type. We can explicitly write the fields of a struct by using this notation on the left-hand side of an assignment.

--> p->id = 15122;
--> p->name = "Cap'n Crunch";
--> p->age = "48";
-->

Clone this wiki locally