Popular Posts

Thursday, July 16, 2009

Structures in C

Structure

You may recall the object oriented approach to programming. Forget data concealing, protection, member functions and inheritance and you end up with C structures.

No, seriously, C structures are a nifty way to avoid redundance in data structures. Consider the example in file structs.c. The source introduces two structures:

Plain structure definition:

struct cat {
int age;
char *name;
} mycat;

This is the way to introduce a single structure reference, in this case it is called mycat. You can reference this structure via the mycat-variable from anywhare within this source file.

Structure type definition:

typedef struct {
int age;
char *kind;
} alldogs;

In this case alldogs refers to a type definition, which can be used to declare variables later on. It works just like a normal variable declaration:

alldogs mydogs[3];

To access the variables within structures, there are two ways, depending on the type of variable which is used to refer to the structure data:

Immediate reference:

alldogs mydogs;
mydogs.age = 15;
mydogs.kind = "keeshond";

The simplest way to use structures is to reference them directly and you have access to the member variables with the '.'-operator. You can create arrays of structure variables, but using the pointer arithmetic method to access array elements should be avoided. There is a substantial amount of hidden magic behind memory allocation and data alignment, and the best way to avoid trouble is to not do anything exotic with structure arrays.

Pointer to a structure:

alldogs *mydogs;
/* allocate memory for the mydogs-structure before doing the following! Use
* malloc()!
*/
mydogs->age = 15;
mydogs->kind = "rottweiler";

The mydogs-variable is a pointer and we have to use the "arrow" style notation to reference the structure members. You could also use this kind of style: (* mydogs).age = 15;

No comments: