Dynamically allocated Array

Download Report

Transcript Dynamically allocated Array

C/C++ Training
Programming C/C++ on Eclipe
Trình bày : Ths HungNM
ADVANCED USER OF POINTER




Dynamic storage of allocation.
Dynamically allocated string.
Dynamically allocated array.
Deallowcating storage.
EcoSoftware
Training C/C++
2
Dynamic storage of allocation



The ability to allocate storage during program
execution
Using dynamic storage allocation, we can design
data structure as needed.
Memory allocation functions.
EcoSoftware
Training C/C++
3
Dynamic storage of allocation

Null pointer :
When the memory allocation is call that posibility it
won’t be able to locate a block of memory large
enough to satify our request.
 Function will be result null pointer.
 Example.

EcoSoftware
Training C/C++
4
Dynamically allocated String

Using malloc.

Syntax :

If you want to allocate space for a string of n charaters.
• (note: sizeofchar(char) = 1);
• char *p = (char*)malloc(n+1);
Memory allocated using malloc isn’t clear.
 Using strcpy is one way to
init value.
strcpy(p,abc)

EcoSoftware
Training C/C++
5
Example Dynamically allocated String
EcoSoftware
Training C/C++
6
Dynamically allocated Array




Using malloc can allocate space for an array.
The calloc fucntion sometime use instead.
The realloc function allow us to make an array
“grow” or “shrink”.
Using malloc to allocate for an array.

Syntax :
• datatype *pointer = (datatype *)malloc(n*sizeof(datatype ));

Example :
• int *a = (int*)malloc(n*sizeof(int)) ;
EcoSoftware
Training C/C++
7
Using calloc to allocate for an array.

It sometime better than malloc.

Syntax :

Example :
• int *a = (int *)calloc(n,sizeof(int));
EcoSoftware
Training C/C++
8
Using realloc to allocate for an array.




We have allocate memory for an array. It too
large or too small.
The realloc function can resize the array to better.
allocate function in <stdlib.h>.
Syntax :
p must point to memory block obtained by a provious
call of malloc or calloc or realloc.
 size paramater represent the new size of the block

EcoSoftware
Training C/C++
9
Using realloc to allocate for an array.

Role of realloc fucntion.
EcoSoftware
Training C/C++
10
Deallocating storage.


Using free function for deallocate.
Syntax :


void free(void *p);
Example :
char *p = (char*)malloc(4);
 free(p);

EcoSoftware
Training C/C++
11
End
• Thank You
EcoSoftware
Training C/C++
12