Lesson 7: Structures
Welcome to the seventh lesson. This is my first lesson
that I will explain classes. However,
I will explain more about structures, because they can
be useful, and they are a good way
to get a feel for how a class works.
What are structures? They are a way to store more than
one data-type under the same name.
Fore example:
#include <string.h> //For
strcpy
struct database
{
int age;
char name[20];
float salary;
};
void main()
{
database employee;
employee.age=22;
strcpy(employee.name, "Joe");
employee.salary=12000.21;
}
Don't worry about the name[20]. That is just an array.
It can hold more than one
character all called under the same name. They are used
like strings. I will do my next
lesson on arrays, I promise, because they are very
important. The struct database declares
that database has three variables in it, age, name, and
salary.
Eventually, you can use database like a variable type
like int. You can create an employee
with the database type like I did above. Then, to modify
it you call everything with the
employee. in front of it. You can also return structures
from functions by defining their
return type as a structure type. Example:
struct database fn();
You can make arrays of structures as well. I will show
you how to do this in lesson 8.
That will be up in a few days. I suppose I should
explain unions a little bit. They are
like structures except that all the variables share the
same memory. When a union is
declared the compiler allocates enough memory for the
largest data-type in the union.
To access the union you use the . like in structures.
Also, if you are accessing the union
of structure through a pointer use the -> operator. for
example, database->employee . The
most useful thing about unions is that you can
manipulate the bytes of the data-types. You
might want to see what you can do if you understand that
sort of stuff. Personally, I have
never used a union.
|