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

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

236 εμφανίσεις

UFS003C3 Lecture 15

Data type in C & C++

Using the STL

Arrays in C

Arrays are a very simple form of storage in C

int list[20];

char word[30];

struct thing mylist[10];

Access is simple via an index

x = list[9];



Always remember C arrays start at 0 and go to

Pointers and arrays

Pointers can easily be used with C arrays

Char *cp, word[20];

strcpy(word,”hello borld”);

cp=word; //or &word[0]

*(cp+7)=‘w’; //same as word[7]=‘w’

Always remember

char *cp

is not the same as

char word[20];

Arrays in C

Positive points

Arrays are a very
convenient & fast
access method of data

They can be randomly

Very easy to use data

Negative points

They are of fixed size
at compilation time .i.e
they can’t grow/shrink

It is difficult to
insert/delete data

Dynamic memory access in C

Frequently a program will require memory
to be dynamically created and deleted
during the program’s execution time.

The data must be requested through a
library called malloc and released by free.

These routines use pointers to memory
and will create or free a requested size of

Using malloc()

malloc is used to request memory from a
system area called the ‘heap’

char *cp;

cp = (char *) malloc(80);

if ( cp != NULL ) …….

The pointer cp now points to a block of 80

NULL can be returned if there is no or not
enough memory.

Using free()

Free is used to free up a block of memory
previously allocated by malloc().

char *cp;

cp = (char *) malloc(80);

……..doing something with the memory


Data in freed memory will be inaccessible and

Can only free memory that has been ‘malloced’

Arrays and pointers in C++

C++ allows the full use of arrays and
pointer access in the same way that C

So any access in C is permissible in C++

However C++ has better ways of doing
some more complex data structure access
controls and more clearly defined memory

Memory allocation in C++

Dynamic memory allocation is simpler in
C++ and often automatic

With pre
created classes the memory
allocation is dealt with by the constructor
and other methods

Explicit requests for heap storage can be
made with the new keyword.

Implicit memory allocation

When using a library class, such as string, for
example, the constructors in that class will
automatically do the memory allocation.

string s(“hello”), t, u;

t = “world”;

U = s + t;

All the memory allocation is dealt with either by
the constructor or the member functions.

Explicit memory allocation

C++ has the new operator. This allocates
heap memory for specified objects or
classes of objects

int *p = new int;

The memory can be released using the
delete operator

delete p;

Explicit memory allocation

The new operator can actually be used to
create arrays which are dimensioned at
run time.

int n;

cout << “enter an array length “ ;

cin >>n;

char * cp = new char[n];

The array is called with new and the
dimension inputted.