Lesson 4: A compound data type
Purpose: |
Introduce the struct data type.
|
Contents: |
The struct data type, use of typedef .
|
References: |
The tutorialspoint about
There is also relevant material in wikibooks: C Programming. |
Composite data type data type
There is a compound data type in C calledstruct
.
In an array, all the elements are of the same type and accessed using indexing.
In a struct
the elements are labeled and can be of different type.Examples:
struct Point {
int x, y;
};
struct Person {
char *name;
int age;
};
It is then possible to create variables of these types:
struct Point a, b, c;
struct Point d = {0, 0};
struct Person p1;
struct Person p2 = {"Charlie", 12};
As seen, the fields can be initialized in the declaration.
The fields can be accessed using a "dot notation".
Examples:
a.x = 3;
b.y = a.x*a.x;
printf("Name: %s of age %d\n", p2.name, p2.age);
Variable of struct
type can be assigned as ordinary variables:
Examples:
c = a;
p1 = p2;
and also returned as function values.
It becomes quite cumbersome to repeat struct Person
in every declaration which leads us to introduce typedef
Type aliases
It is possible to create aliases for types in C. Examples.
typedef float real;
typedef char string[100];
typedef int * intPointer;
real x, y, z;
string name, address;
intPointer ip, jp;
It is particular useful for struct
s:
struct Point {
int x, y;
};
typedef struct Point Point;
Point a, b, c;
The struct
and typedef
can be combined:
typedef
struct Point {
int x, y;
} Point;
Point a, b, c;
Exercises
-
Write a function that asks the user for a person's name and
and age.
Try three different ways of returning the result:-
using a parameter of type
*Person
, -
as a
Person
function value and -
as a pointer to
Person
.
-
using a parameter of type
-
Write three
main
functions showing how the three versions above should be called. -
The following
struct
is used to store a, from the beginning, unknown number of integers:typedef struct Container { int *buffer; // Pointer to the storage int size; // Allocated size int used; // Current number of used places } Container;The integers are stored from the beginning so the firstused
is the index for the first free position. The container is full whenused == size
.A function for creating containers is given:
Container *makeContainer(int initialSize) { Container *c = (Container *)malloc(sizeof(container)); (*c).size = initialSize; (*c).used = 0; (*c).buffer = (int *)malloc(initialSize*sizeof(int)); return c: }Make sure that you understand the code!Write a function
int store(int data, Container *c)
that stores data in the first free position and returns the index of that position. If the container is full, it should be expanded.
Go to next lesson.
Dölj style3dev.css för att bli av med annoteringarna!