Tutorial 6 – Structs

In the last tutorial we saw how we could simplify our code and do more complex things by using functions. C has yet more benefits that we can take advantage of. Lets say we want to model a real life situation, for example we want to store some information on a group of people. We could do that with our old code but we’d need to create a new variable for each piece of data we want to store on each person e.g:

float person1Height = 1.6f;
int person1Age = 21;
float person2Height = 1.7f;
int person2Age = 30;

This isn’t terrible but there are better solutions. Lets take a look at structs. Here is an example of how to use structs:

struct structName
    int variable1;
    float variable2;

The above code says that there is a type of structure called “structName” which contains the 2 variables named within the brackets. Here is an example of a struct that contains a person’s data and how we would go about accessing that data:

struct person
    int age;
    float height;

int main()
    person dave;
    dave.age = 33;
    dave.height = 1.65f;

    return 0;

As you can see, structs can really simplify not only the code for your program, but also the way you conceptualise the data within it.

  1. No comments yet.
  1. No trackbacks yet.

Tell me what you think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: