10.09.2013 Views

1. Advanced Data Structure using C++

1. Advanced Data Structure using C++

1. Advanced Data Structure using C++

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

LECTURE NOTES OF ADVANCED DATA STRUCTURE (MT-CSE 110)<br />

Malloc Function:‐<br />

Malloc requires one argument ‐ the number of bytes you want to allocate<br />

dynamically.<br />

If the memory allocation was successful, malloc will return a void pointer ‐ you<br />

can assign this to a pointer variable, which will store the address of the<br />

allocated memory.<br />

If memory allocation failed (for example, if you're out of memory), malloc will<br />

return a NULL pointer.<br />

Passing the pointer into free will release the allocated memory ‐ it is good<br />

practice to free memory when you've finished with it.<br />

This example will ask you how many integers you'd like to store in an array. It'll<br />

then allocate the memory dynamically <strong>using</strong> malloc and store a certain number<br />

of integers, print them out, then releases the used memory <strong>using</strong> free.<br />

#include <br />

#include /* required for the malloc and free functions */<br />

int main() {<br />

int number;<br />

int *ptr;<br />

int i;<br />

printf("How many ints would you like store? ");<br />

scanf("%d", &number);<br />

ptr = malloc(number*sizeof(int)); /* allocate memory */<br />

if(ptr!=NULL) {<br />

for(i=0 ; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!