Structures

by
Matthew Martin
Structures are part of the C programming language but
can also be used in C++. The only difference is that in C++ structures
are treated as a class with all its members being public by default, although
it is possible to make them private by using the private keyword in the
declaration.
Content
Declaring
A Structure
Differences
Between Structures In C And C++
Arrays
Of Structures

top
of page
Declaring A Structure
Structures are declared using the keyword struct. This is done using the
following syntax:
struct struct-name: inheritance-list {
//public members by default
…
}object-list;
e.g.:
struct studentrecord {
int codenumber;
char firstname[10];
char lastname[15];
char malefemale;
bool registered;
}
In the above example the structure is called studentrecord
and it contains the integer codenumber, two char arrays (strings), a char
variable and a Boolean variable.
top
of page

Differences Between Structures In C And C++
In C there are no classes, so structures are treated as a special grouping
of variables. In C structures can only contain data members, there can
be no functions. There is no such thing as encapsulation in C, so effectively
everything is public.
top
of page

Arrays Of Structures
It is possible to declare arrays of structures. The syntax is:
struct struct-name {
//members
…
} struct-array-name[n];
Using the example of the studentrecord structure from above, an
array using this structure can be declared for 100 students, called students:
e.g.:
struct studentrecord {
int codenumber;
char firstname[10];
char lastname[15];
char malefemale;
bool registered;
} students[100];
Sometimes an array of structures is referred to as a structural-array.

by Matthew
Martin |