Sunday, 19 August 2012

C++ Programming Tutorial Lesson #8 - Structures


What is a structure?

A structure is used to group variables together under one name. If you have a student structure for example then you will group the student number and student name together.

How to create and use a structure

The first thing to do when creating a structure is to use the struct keyword followed by the structure name. You need to put curly brackets after that which will contain the things that make up the structure. Always remember to put a semi-colon after the curly brackets. Here is an example of a structure called student.
#include<iostream>

struct student
{
};

int main()
{
   return 0;
}
You must now put the variables that belong to the structure inside the curly brackets. For the following example we will have a student number and student name.
struct student
{
   int num;
   char name[25];
};
The struct is only a definition for what the structure will look like so we have to now declare a structure in memory of the student type. We will call it stu.
int main()
{
   student stu;
   return 0;
}
You must use a dot between the structure name and the sub item to access it. Here is an example of how to set their values and print them out.
student stu;
stu.num = 12345;
strcpy(stu.name,"John Smith");
cout << stu.num << endl;
cout << stu.name << endl;

Pointers to structures

When you are using a pointer to a structure then you must use a -> instead of a dot. Here is an example of how to set the student number using a pointer to the student structure.
student stu;
student *sp = &stu;
sp->num = 10000;