A struct
is a way of creating a composite type in C. Basically it allows one to group of attributes together. It is a user-defined data structure.
The are declared as follows:
struct Color { uint8_t r; uint8_t g; uint8_t b; };
Typically this declaration would appear in a header file. The Color struct can be used like this:
struct Color color; color.r = 0; color.g = 0; color.b = 0;
This creates a Color
"object" and then assigns the r
, g
, and b
fields to zero (for black).
We can make use of a typedef
to clean up the syntax slightly:
typedef struct { uint8_t r; uint8_t g; uint8_t b; } Color;
which allows us to now declare a Color struct like this:
Color color; color.r = 0; color.g = 0; color.b = 0;
This looks a lot like how references are declared in Java, but it is really quite different. Here the compiler is actually allocating space (on the stack) for the "object". In Java, a declaration like Color color
would just allocate space (also on the stack) for a reference to an object. The actual object would not be created until a new Color()
operation was performed.
We can create a pointer (like a reference in Java) to a Color
in C as follows:
Color color; Color *ptr = &color; ptr->r = 0; ptr->g = 0; ptr->b = 0;
The arrow operator ->
allows us to access a field of an "object" through a pointer. It is equivalent to (*ptr).x = 0;
.
It is possible for a struct to contain other structs. Consider the following example which results in a Rectangle.
#include <inttypes.h> #ifndef COLOR_H #define COLOR_H typedef struct { uint8_t r; uint8_t g; uint8_t b; } Color; #endif
#include <inttypes.h> #ifndef POINT_H #define POINT_H typedef struct { int16_t x; int16_t y; } Point; #endif
#include <inttypes.h> #ifndef RECTANGLE_H #define RECTANGLE_H typedef struct { Point upperLeft; Point lowerRight; Color color; } Rectangle; #endif
Making a white, 10 x 10 square centered at the origin would require:
Rectangle rect; rect.upperLeft.x = -5; rect.upperLeft.y = 5; rect.lowerRight.x = 5; rect.lowerRight.y = -5; rect.color.r = 255; rect.color.g = 255; rect.color.b = 255;