In: Computer Science
Explain how a full array in C can be expanded to hold more values. In your answer make sure you mention the function calls required, and anything else that is necessary to perform this task. Give a small example where an array of 100 integers is resized to be able to now store 200 integers.
Array in general is a collection of homogenous elements which are stored at continous location and normally the size of the array is fixed.
But what is there we need to change the size of the array. For example, 3 more students records are added to the array containing their height.
Hence for these purposes dynamic memory allocation is required. Under <stdlib.h> there are few function that help you to perform dynamic memory allocation in C.
1) malloc - this function will let you allocate memory dynamically while creating array. The return type of this function is a void pointer which can be cast to any type.
example -
int * ptr = (int*) malloc ( 10 * sizeof(int));
assuming the size of integer is 4 bytes then this will allocate a block of 40 bytes of memory and will return the pointer to that location.
2) realloc() - size of the dynamically allocated memory can be changed using realloc(). it should only be used for those arrays which are dynamically allocated, Otherwise it will show so weird behavior.
what realloc does is it deallocate the old object pointed by the pointer and makes the pointer pointer to the new object. The values stored in the new object are same as the previous values.
example - in the previous example we had array of size 10, suppose we need to add 5 more values . This is how we are going to solve the problem using realloc.
ptr_new=(int*) realloc(ptr,sizeof(int)*5);
code -
#include<stdio.h>
#include<stdlib.h>
int main()
{
int * ptr=(int *)malloc(sizeof(int)*100);
int i;
for(i=0;i<100;i++)
{
ptr[i]=i;
}
printf("after malloc \n");
for(i=0;i<100;i++)
{
printf("%d ",ptr[i]);
}
int * newptr=(int
*)realloc(ptr,sizeof(int)*200);
printf("\n");
for(i=100;i<200;i++)
{
newptr[i]=i;
}
printf("after realloc \n");
for(i=0;i<200;i++)
{
printf("%d ",newptr[i]);
}
}
output -