Lab 8: Dynamic memory allocation -

jaspersugarlandΛογισμικό & κατασκευή λογ/κού

14 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

78 εμφανίσεις

CO2402 Advanced Programming with C++



Tony Nicol

Introduction to d
memory allocation


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

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.


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


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
, print each set of details in the form specified in
2. Release all
heap me
mory before

closing the application.


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.



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
On return from the

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

before closing the application.