0% found this document useful (0 votes)
33 views

7-9. Dynamic Array and DMA-1

The document discusses dynamic memory allocation using malloc in C. It explains problems with static arrays and introduces dynamic arrays which allocate memory dynamically as needed. It provides examples of using malloc to allocate memory for arrays and structures and covers related functions like free and realloc.

Uploaded by

Pratham Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

7-9. Dynamic Array and DMA-1

The document discusses dynamic memory allocation using malloc in C. It explains problems with static arrays and introduces dynamic arrays which allocate memory dynamically as needed. It provides examples of using malloc to allocate memory for arrays and structures and covers related functions like free and realloc.

Uploaded by

Pratham Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

B.

TECH III SEM CSE


ACADEMIC YEAR: 2022-2023

Course Name: Data Structure and Algorithm


Topic: Dynamic Array and Dynamic Memory Allocation
Course code : CS 2103
Credits : 4
Mode of delivery : Hybrid (Power point presentation)
Faculty : Mr. Satpal Singh Kushwaha
Email-id : satpal.singh@jaipur.manipal.edu
Assessment
criteria’s

Assignment
quiz
Mid term examination –
II
End term Examination
Dynamic Memory
Allocation

3
Problem with Arrays
◼ Sometimes
 Amount of data cannot be predicted beforehand
 Number of data items keeps changing during program
execution
◼ Example: Serach for an element in an array of N elements
◼ One solution: find the maximum possible value of N and
allocate an array of N elements
 Wasteful of memory space, as N may be much smaller
in some executions
 Example: maximum value of N may be 10,000, but a
particular run may need to search only among 100
elements
◼ Using array of size 10,000 always wastes memory
in most cases 4
Dynamic Array

top = 4

6 1 7 8
0 1 2 3 4 5
Dynamic Array

top = 4 insert 5

6 1 7 8
0 1 2 3 4 5
Dynamic Array

top = 5

6 1 7 8 5
0 1 2 3 4 5
Dynamic Array

top = 5
insert 2

6 1 7 8 5
0 1 2 3 4 5
Dynamic Array

top = 6
insert 3

6 1 7 8 5 2
0 1 2 3 4 5
Dynamic Array

top = 6
insert 3

6 1 7 8 5 2 !The array is full and


0 1 2 3 4 5 there is no room for a
new item!
Dynamic Array

top = 6
insert 3

6 1 7 8 5 2
0 1 2 3 4 5 So we will create a
new, bigger array …
Dynamic Array

top = 6
insert 3

6 1 7 8 5 2
0 1 2 3 4 5 So we will create a
new, bigger array …

0 1 2 3 4 5 6 7 8 9 10 11
Dynamic Array

top = 6
insert 3

6 1 7 8 5 2
0 1 2 3 4 5 … copy the
elements of the old
array into it …

0 1 2 3 4 5 6 7 8 9 10 11
Dynamic Array

insert 3

6 1 7 8 5 2
0 1 2 3 4 5 … copy the
elements of the old
top = 6
array into it …

6 1 7 8 5 2
0 1 2 3 4 5 6 7 8 9 10 11
Dynamic Array

insert 3

6 1 7 8 5 2
0 1 2 3 4 5 … and finally insert
top = 7 3 into the new array.

6 1 7 8 5 2 3
0 1 2 3 4 5 6 7 8 9 10 11
Dynamic Array

Frees previously
allocated space
6 1 7 8 5 2
0 1 2 3 4 5

top = 7

6 1 7 8 5 2 3
0 1 2 3 4 5 6 7 8 9 10 11
Better Solution
◼ Dynamic memory allocation
 Know how much memory is needed after the program
is run
◼ Example: ask the user to enter from keyboard
 Dynamically allocate only the amount of memory
needed
◼ C provides functions to dynamically allocate
memory
 malloc, calloc, realloc

17
18
Memory Allocation Functions
◼ malloc
 Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space
◼ calloc
 Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
◼ free
 Frees previously allocated space.
◼ realloc
 Modifies the size of previously allocated space.
◼ We will only do malloc and free
19
20
If space is insufficient, allocation fails and
returns a NULL pointer.

21
22
If space is insufficient, allocation fails and
returns a NULL pointer.
23
24
25
26
If space is insufficient, allocation fails and
returns a NULL pointer.
27
/*----------------------------------------------------
* Program example of creating dynamic array in C using malloc
*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
//Creating the int pointer to store
//the address return by malloc
int *ptr=NULL;

//Declaring the variable i for array index to use in for loop


//to access the array elements. len will be used to calculate
//size of array and in for loop condition.
int i,len=0;

//Prompt user to enter the size of array


printf("ENTER THE SIZE OF ARRAY:");

//Reading the array size and storing in len variable


scanf("%d",&len);

//allocating the dynamic memory and store the address


//returned by malloc. malloc returns address keeping in
//void pointer. Since, we want to store int type of
//data so, type cast it into int pointer.
//
ptr=(int*)malloc(len*sizeof(int));
28
//Ask the user to enter all the elements
printf("ENTER THE ELEMENTS:");
//assigning the values to the array
for(i=0;i<len;++i){
//write the values in memory location
scanf("%d", &ptr[i]);
}

//Read the values from the memory location and


//display on the screen

printf("Array elements are \n");


for(i=0;i<len;++i)
{
printf("%d,", ptr[i]);
}

// free the memory


free(ptr);
return 0;
}

29
Example
int main() printf("Input heights for %d
{ students \n",N);
int i,N; for (i=0; i<N; i++)
float *height; scanf ("%f", &height[i]);
float sum=0,avg;
for(i=0;i<N;i++)
printf("Input no. of students\n"); sum += height[i];
scanf("%d", &N);
avg = sum / (float) N;
height = (float *)
malloc(N * sizeof(float)); printf("Average height = %f \n",
avg);
free (height);
return 0;
}

30
Can we allocate only arrays?
◼ malloc can be used to allocate memory for
single variables also
p = (int *) malloc (sizeof(int));
 Allocates space for a single int, which can be
accessed as *p
◼ Single variable allocations are just special
case of array allocations
 Array with only one element

31
malloc( )-ing array of structures
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[20];
int roll;
float SGPA, CGPA;
} person;

void main()
{
person *student;
int i,j,n;
printf("Enter number of students");
scanf("%d", &n);
student = (person *)malloc(n*sizeof(person));

32
malloc( )-ing array of structures
for (i=0; i<n; i++)
{
printf("Enter name");
scanf("%s", student[i].name);
printf("Enter roll number");
scanf("%d", &student[i].roll);
printf("Enter SGPA");
scanf("%f", &student[i].SGPA);
}

for (i=0; i<n; i++)


{
printf("%s", student[i].name);
printf("%d", student[i].roll);
printf("%f", student[i].SGPA);
}
}

33
Static array of pointers
#define N 20
#define M 10
int main()
{
char word[N], *w[M];
int i, n;
scanf("%d",&n);
for (i=0; i<n; ++i) {
scanf("%s", word);
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char));
strcpy (w[i], word) ;
}
for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]);
return 0;
}

34
Static array of pointers
#define N 20 Output
#define M 10 4
int main() Tendulkar
{ Sourav
char word[N], *w[M]; Khan
int i, n; India
scanf("%d",&n); w[0] = Tendulkar
for (i=0; i<n; ++i) { w[1] = Sourav
scanf("%s", word); w[2] = Khan
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); w[3] = India
strcpy (w[i], word) ;
}
for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]);
return 0;
}

35
How it will look like malloc()
w
0 T e n d u l k a r \0
1 S o u r a v \0

2 K h a n \0

3 I n d i a \0

36
Pointers to Pointers
◼ Pointers are also variables (storing addresses),
so they have a memory location, so they also
have an address
◼ Pointer to pointer – stores the address of a
pointer variable

int x = 10, *p, **q;


p = &x;
q = &p;
printf(“%d %d %d”, x, *p, *(*q));

will print 10 10 10 (since *q = p)


37
Allocating Pointer to Pointer
int **p;
p = (int **) malloc(3 * sizeof(int *));

p[0]
p int ** int *
p[1] int *
p[2] int *

38
2D array
#include <stdlib.h>

int main()
{
int **array;
array = (int**) malloc(nrows * sizeof(int *));

for(i = 0; i < nrows; i++)


{

array[i] = (int*)malloc(ncolumns * sizeof(int));

{
39
2D array

x 0
Int main()
{ 1
2
*x; pointer to x[0][0]
3
*(x+1); pointer to x[1][0]

**(x+1); Value x[1][0]

*(*(x+1)+4) Value x[1][4]

*((*x)+8) Value x[0][8] 9


}

40
Dynamic Allocation of 2-d Arrays
int **allocate (int h, int w)
{ void read_data (int **p, int h, int w)
int **p; Allocate array {
int i, j; of pointers int i, j;
for (i=0;i<h;i++)
p = (int **) malloc(h*sizeof (int *) ); for (j=0;j<w;j++)
for (i=0;i<h;i++) scanf ("%d", &p[i][j]);
p[i] = (int *) malloc(w * sizeof (int)); }
return(p);
} Allocate array of Elements accessed
integers for each like 2-D array elements.
row

41
Contd.
void print_data (int **p, int h, int w) int main()
{ {
int i, j; int **p;
for (i=0;i<h;i++) int M, N;
{ printf ("Give M and N \n");
for (j=0;j<w;j++) scanf ("%d%d", &M, &N);
printf ("%5d ", p[i][j]); p = allocate (M, N);
printf ("\n"); read_data (p, M, N);
} printf ("\nThe array read as \n");
} print_data (p, M, N);
return 0;
}

42
Contd. int main()
{
void print_data (int **p, int h, int w)
int **p;
{
int M, N;
int i, j;
printf ("Give M and N \n");
for (i=0;i<h;i++)
scanf ("%d%d", &M, &N);
{
p = allocate (M, N);
for (j=0;j<w;j++)
read_data (p, M, N);
printf ("%5d ", p[i][j]);
printf ("\nThe array read as \n");
printf ("\n");
print_data (p, M, N);
} Give M and N
return 0;
} 33
123 }
456
789
The array read as
1 2 3
4 5 6
7 8 9 43

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy