Lab 8: Dynamic memory allocation - Tony.seriouslyinternet.com

jaspersugarlandSoftware and s/w Development

Dec 14, 2013 (3 years and 9 months ago)

87 views

CO2402 Advanced Programming with C++

Page
1

of
1


Tony Nicol

Introduction to d
ynamic
memory allocation



1.

Write a program that declares a structure TDetails. The structure should have
three members. Two characte
r arrays
of 25 chars to
hold
the
first and last
nam
e and an int
to
hold
the
age.


Declare a pointer to a
structure of type Tdetails within main(). Dynamically
allocate memory for the structure then read first name, last name and age from
the keyboard into the structure fields.


Print the

complete structure in the form:


Jim Smith is 23 years old.


Release th
e heap memory before
closing the application.


2.

In a new file, modify the program in 1. The new program should replace the
fixed arrays in the structure with char pointers. When the structure has been
dynamically allocated, dynamically allocate the first
and second name fields
such that only the required amount of memory is used for the name read from
the keyboard.

You may use a single statically allocated buffer to collect the
user’s input.


Print the contents of the structure as in 1. Release the heap m
emory before

closing the application
.


3.

In a new file modify the program in 2. The new program should declare an
array of 3 pointers to structures of type TDetails. Each element of the array
should be assigned to point to a dynamically allocated structure

where each
structure has the two string fields dynamically allocated. Read three sets of
names and ages into the structures. When all structures have the names and
ages
, print each set of details in the form specified in
question
2. Release all
heap me
mory before

closing the application.


4.

Dynamically allocate a structure
of type TDetails
in main.
The name arrays
should be declared as 25 chars each.
Pass the address of the structure to a
function called GetDetails. GetDetails should get the name and ag
e of the user
and copy them into the
structure. On return to main, print the contents of the
structure to the screen.


5.

Modify

the program
and function GetDetails.

The function will dynamically
allocate a structure of type TDetails and dynamically allocate

the first and last
name fields within the structure

and reads the user’s details into the structure
.
The function is called from main and has no parameters. The function returns
a pointer to the newly allocated initialised
structure
.
On return from the

function, p
rint the contents of the structure in m
ain
.
. Release all heap memory

before closing the application.