In: Computer Science
Memory was allocated initially for 5 elements, later
on two more elements added to list. How can
space be managed in such case. Implement the scenario in C.
IN C PROGRAMING
CODE:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *ptr;
// a dynamic array of size 5 is allocated
ptr = (int*) malloc(5 * sizeof(int));
for(int i = 0; i < 5; ++i){
// storing index+1 in the array
*(ptr+i)=i+1;
}
printf("%d\n",*(ptr+4));
// now for example assume 5 is a bit short for us
// so lets extend the size of ptr array
ptr = realloc(ptr, 7 * sizeof(int));
// now we can store value till index 7
for(int i = 0; i < 7; ++i){
// storing index+1 in the array
*(ptr+i)=i+1;
}
printf("%d\n",*(ptr+6));
return 0;
}
OUTPUT:
Please
upvote if you like my answer and comment below if you have
any queries or need any further explanation.