Guides:C/C Crash Course/Structures

From CoderGuide

Jump to: navigation, search

Back to TOC

Structures

A structure allows us to clump a lot of different data into one nice neat container, and reuse that container over and over again. To access variables inside a structure you need to use the dot-operator ".". If you're accessing a pointer to a structure, then you need to use the arrow-operator "->" to access elements of that structure. To define a structure. To define a structure, we can do it in a few ways:

/*Create a definition for the Record structure*/
 
struct Record{
        char name[40];
        int age;
};
 
/*Now lets create a few Record structures to use in our program*/
struct Record rec1;
struct Record rec2;
struct Record recs[20]; /*An array of Record structures*/

When we define the Record structure above, we've basically created a new data type, but have not used that data type yet, until we declare the rec1, rec2, and recs variables below it. Another way is such as:

struct {
        char name[40];
        int age;
}rec;

With this second example, we've created a structure variable, and space has been created for it. We can't create any more structures using this definition because we haven't given the structure a name. We've only given it a variable name to use.

struct Record{
        char name[40];
        int age;
}rec;


Here is a little different, we've declared the rec variable, and also given the structure a name. We can now declare more Record structure variables.

Here's how access members of this structure:

struct Record rec;
struct Record *r;
 
r=&r;
 
rec.age=13;
strcpy(rec.name,"Johnny Doe");
printf("%d",r->age);

We can also have structures in structures:

struct {
        char name[40];
        struct {
                char year;
                char month;
                char day;
        }birthday;
}rec;
 
rec.birthday.year=94;
rec.birthday.month=1;
rec.birthday.day=2;

Or like this:

struct Date{
        char year;
        char month;
        char day;
};
 
struct Record{
        char name[40];
        struct Date birthday;
};

Now that we know how to use structures, let's do something useful with them in a simple address book program!

Personal tools