0% found this document useful (0 votes)
15 views15 pages

Chapter One

The document discusses data structures called structures in C/C++. It explains that a structure defines a new data type that groups together other primitive or user-defined data types under a single name. Structures allow declaring variables of complex user-defined types. Pointers to structures can be declared similarly to pointers to primitive types, using the -> operator to access members of a struct through a pointer. Arrays of structures allow storing multiple struct objects, and structures enable building databases by grouping related data together under a single type.

Uploaded by

amareadios60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

Chapter One

The document discusses data structures called structures in C/C++. It explains that a structure defines a new data type that groups together other primitive or user-defined data types under a single name. Structures allow declaring variables of complex user-defined types. Pointers to structures can be declared similarly to pointers to primitive types, using the -> operator to access members of a struct through a pointer. Arrays of structures allow storing multiple struct objects, and structures enable building databases by grouping related data together under a single type.

Uploaded by

amareadios60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter One: Structures

1.1. Structures

✓ A data structure is a set of diverse types of data that may have different lengths grouped
together under a unique declaration. Its form is the following:

struct model_name {

type1 element1;

type2 element2;

type3 element3;

} object_name;

where model_name is a name for the model of the structure type and the optional parameter
object_name is a valid identifier (or identifiers) for structure object instantiations. Within curly
brackets { } they are the types and their sub-identifiers corresponding to the elements that compose
the structure.

✓ If the structure definition includes the parameter model_name (optional), that parameter
becomes a valid type name equivalent to the structure. For example:

struct products {

char name [30];

float price;

};

products apple;

products orange, banana;

1
✓ We have first defined the structure model products with two fields: name and price, each of a
different type. We have then used the name of the structure type (products) to declare three
objects of that type: apple, orange and banana.
✓ Once declared, products become a new valid type name like the primitive ones (int, char or
short) and we can declare objects (variables) of that type.
✓ The optional field object_name that can go at the end of the structure declaration serves to
directly declare objects of the structure type. For example, we can also declare the structure
objects apple, orange and banana this way:

struct products {

char name [30];

float price;

} apple, orange, banana;

✓ Moreover, in cases like the last one in which we took advantage of the declaration of the
structure model to declare objects of it, the parameter model_name (in this case products)
becomes optional. Although if model_name is not included it will not be possible to declare
more objects of this same model later.
✓ It is important to clearly differentiate between what is a structure model, and what is a
structure object. Using the terms we used with variables, the model is the type, and the object
is the variable. We can instantiate many objects (variables) from a single model (type).
✓ Once we have declared our three objects of a determined structure model (apple, orange and
banana) we can operate with the fields that form them. To do that we have to use a point (.)
inserted between the object name and the field name. For example, we could operate with any
of these elements as if they were standard variables of their respective types:

apple.name
apple.price
orange.name
orange.price
banana.name
banana.price

2
each one being of its corresponding data type: apple.name, orange.name and banana.name are of
type char[30], and apple.price, orange.price and banana.price are of type float.

Another example about movies:


// Example about structures

#include <iostream.h> cout << "My favourite movie is:\n ";

#include <string.h> printmovie (mine);

#include <stdlib.h> cout << "And yours:\n ";

struct movies_t { printmovie (yours);

char title [50]; return 0;

int year; }

} mine, yours; void printmovie (movies_t movie)

void printmovie (movies_t movie); {

int main () cout << movie.title;

{ cout << " (" << movie.year << ")\n";

char buffer [50]; }

strcpy (mine.title, "Gudifecha");

mine.year = 2003;
Enter title: SemayawiFeres
cout << "Enter title: ";
Enter year: 2005
My favourite movie is:
cin.getline (yours.title,50);
Gudifecha (2003)
cout << "Enter year: "; And yours:
SemayawiFeres (2005)
cin.getline (buffer,50);

yours.year = atoi (buffer);

cout << "My favourite movie is:\n ";

printmovie (mine);

cout << "And yours:\n ";

printmovie (yours); 3
✓ The example shows how we can use the elements of a structure and the structure itself as
normal variables. For example, yours.year is a valid variable of type int, and mine.title is a
valid array of 50 chars.
✓ Notice that mine and yours are also treated as valid variables of type movies_t when being
passed to the function printmovie(). Therefore, one of the most important advantages of
structures is that we can refer either to their elements individually or to the entire structure as
a block.
✓ Structures are a feature used very often to build data bases, specially if we consider the
possibility of building arrays of them.

// array of structures cin.getline (films[n].title,50);


#include <iostream.h> cout << "Enter year: ";
#include <stdlib.h> cin.getline (buffer,50);
#define N_MOVIES 5 films[n].year = atoi (buffer);
struct movies_t { }
char title [50]; cout << "\nYou have entered these movies:\n";
int year; for (n=0; n<N_MOVIES; n++)
} films [N_MOVIES]; printmovie (films[n]);
void printmovie (movies_t movie); return 0;
int main () }
{ void printmovie (movies_t movie)
char buffer [50]; {
int n; cout << movie.title;
for (n=0; n<N_MOVIES; n++) cout << " (" << movie.year << ")\n";
{ }
cout << "Enter title: ";

4
Enter title: Alien
Enter year: 1979
Enter title: Blade Runner
Enter year: 1982
Enter title: Matrix
Enter year: 1999
Enter title: Rear Window
Enter year: 1954
Enter title: Taxi Driver
Enter year: 1975
You have entered these movies:
Alien (1979)
Blade Runner (1982)
Matrix (1999)
Rear Window (1954)
Taxi Driver (1975

1.2. Pointers to structures

✓ Like any other type, structures can be pointed by pointers. The rules are the same as for any
fundamental data type: The pointer must be declared as a pointer to the structure:

struct movies_t {

char title [50];

int year;

};

movies_t amovie;

movies_t * pmovie;

Here amovie is an object of struct type movies_t and pmovie is a pointer to point to objects of
struct type movies_t. So, the following, as with fundamental types, would also be valid:

5
pmovie = &amovie;

Ok, we will now go with another example, that will serve to introduce a new operator:

6
Enter title: Matrix
// pointers to structures Enter year: 1999
#include <iostream.h> You have entered:
Matrix (1999)
#include <stdlib.h>

struct movies_t {

char title [50];

int year;

};

int main ()

char buffer[50];

movies_t amovie;

movies_t * pmovie;

pmovie = & amovie;

cout << "Enter title: ";

cin.getline (pmovie->title,50);

cout << "Enter year: ";

cin.getline (buffer,50);

pmovie->year = atoi (buffer);

cout << "\nYou have entered:\n";

cout << pmovie->title;

cout << " (" << pmovie->year << ")\n";

7
return 0;

The previous code includes an important introduction: operator ->. This is a reference operator
that is used exclusively with pointers to structures and pointers to classes. It allows us not to have
to use parenthesis on each reference to a structure member. In the example we used:

pmovie->title

that could be translated to:

(*pmovie).title

both expressions pmovie->title and (*pmovie).title are valid and mean that we are evaluating the
element title of the structure pointed by pmovie. You must distinguish it clearly from:

*pmovie.title

that is equivalent to

*(pmovie.title)

and that would serve to evaluate the value pointed by element title of structure movies, that in this
case (where title is not a pointer) it would not make much sense. The following panel summarizes
possible combinations of pointers and structures:

8
Expression Description Equivalent

pmovie.title Element title of structure pmovie

pmovie->title Element title of structure pointed by pmovie (*pmovie).title

*pmovie.title Value pointed by element title of structure pmovie *(pmovie.title)

1.3. Nesting structures

Structures can also be nested so that a valid element of a structure can also be another structure.

struct movies_t {

char title [50];

int year;

struct friends_t {

char name [50];

char email [50];

movies_t favourite_movie;

} bekele, abebe;

friends_t * pfriends = &bekele;

Therefore, after the previous declaration we could use the following expressions:

bekele.name
abebe.favourite_movie.title
bekele.favourite_movie.year
pfriends->favourite_movie.year

(where, by the way, the last two expressions are equivalent).

9
The concept of structures that has been discussed in this section is the same as used in C language,
nevertheless, in C++, the structure concept has been extended up to the same functionality of a
class with the peculiarity that all of its elements are considered public.

1.4. User defined data types

We have already seen a data type that is defined by the user (programmer): the structures. But in
addition to these there are other kinds of user defined data types:

Definition of own types (typedef).

C++ allows us to define our own types based on other existing data types. In order to do that we
shall use keyword typedef, whose form is:

typedef existing_type new_type_name;

where existing_type is a C++ fundamental or any other defined type and new_type_name is the
name that the new type we are going to define will receive. For example:

typedef char C;
typedef unsigned int WORD;
typedef char * string_t;
typedef char field [50];

In this case we have defined four new data types: C, WORD, string_t and field as char, unsigned
int, char* and char[50] respectively, that we could perfectly use later as valid types:

C achar, another char,*ptchar1;


WORD myword;
string_tptchar2;
field name;

typedef can be useful to define a type that is repeatedly used within a program and it is possible
that we will need to change it in a later version, or if a type you want to use has too long a name
and you want it to be shorter.

10
1.5. Unions

Unions allow a portion of memory to be accessed as different data types, since all of them are in
fact the same location in memory. Its declaration and use is similar to the one of structures but its
functionality is totally different:

union model_name {

type1 element1;

type2 element2;

type3 element3;

} object_name;

All the elements of the union declaration occupy the same space of memory. Its size is the one of
the greatest element of the declaration. For example:

union mytypes_t {

char c;

int i;

float f;

} mytypes;

defines three elements:

mytypes.c
mytypes.i
mytypes.f

each one of a different data type. Since all of them are referring to a same location in memory, the
modification of one of the elements will affect the value of all of them.

One of the uses a union may have is to unite an elementary type with an array or structures of
smaller elements. For example,

11
union mix_t{

long l;

struct {

short hi;

short lo;

} s;

char c[4];

} mix;

defines three names that allow us to access the same group of 4 bytes: mix.l, mix.s and mix.c and
which we can use according to how we want to access it, as long, short or char respectively. We
have mixed types, arrays and structures in the union so that you can see the different ways that we
can access the data:

Anonymous unions

In C++ we have the option that unions be anonymous. If we include a union in a structure without
any object name (the one that goes after the curly brackets { }) the union will be anonymous and
we will be able to access the elements directly by its name. For example, look at the difference
between these two declarations:

12
Union anonymous union

struct { struct {

char title[50]; char title[50];

char author[50]; char author[50];

union { union {

float dollars; float dollars;

int yens; int yens;

} price; };

} book; } book;

The only difference between the two pieces of code is that in the first one we gave a name to the
union (price) and in the second we did not. The difference is when accessing members dollars and
yens of an object. In the first case it would be:

book.price.dollars
book.price.yens

whereas in the second it would be:

book.dollars
book.yens

Once again I remind you that because it is a union, the fields dollars and yens occupy the same
space in the memory so they cannot be used to store two different values. That means that you can
include a price in dollars or yens, but not both.

1.6. Enumerations (enum)

Enumerations serve to create data types to contain something different that is not limited to either
numerical or character constants or to the constants true and false.

13
enum model_name {

value1,

value2,

value3,

} object_name;

For example, we could create a new type of variable called color to store colors with the following
declaration:

enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

✓ Notice that we do not include any fundamental data type in the declaration. To say it another
way, we have created a new data type without it being based on any existing one: the type
color_t, whose possible values are the colors that we have enclosed within curly brackets {}.
For example, once declared the colors_t enumeration in the following expressions will be
valid:

colors_t mycolor;
mycolor = blue;
if (mycolor == green) mycolor = red;

In fact our enumerated data type is compiled as an integer and its possible values are any type of
integer constant specified. If it is not specified, the integer value equivalent to the first possible
value is 0 and the following ones follow a +1 progression. Thus, in our data type colors_t that we
defined before, black would be equivalent to 0, blue would be equivalent to 1, green to 2 and so
on.

If we explicitly specify an integer value for some of the possible values of our enumerated type
(for example the first one) the following values will be the increases of this, for example:

14
enum months_t { january=1, february, march, april,may, june, july, august, September, october,
november, december} y2k;

in this case, variable y2k of the enumerated type months_t can contain any of the 12 possible
values that go from january to december and that are equivalent to values between 1 and 12, not
between 0 and 11 since we have made january equal to 1.

Exercise
Suppose we want to create a record of employees of a certain Organization. The record contains
the name, the ID number, title, department, and salary of each employee.

1. Create a suitable structure to hold the aforementioned record of the employees.


2. Write a statement that reserves 1000 contiguous memory spaces to store record.
3. Write a function to accept data for 1000 employees
4. Write a function that increments the salary of each employee by 10%.
5. Write a program that implements the above structure definition.

15

You might also like