If I create an array of size 10 and only 2 elements are stored in array so remaining spaces gets wasted. so how can I solve this problem? (by data structure)
You would use a simple linked list instead of an array, or if you would need to use an array, then you should use realloc()
, which would shrink the array to use only 2 cells, instead of 10.
, like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* ptr = malloc(10 * sizeof(int));
ptr[0] = 4;
ptr[1] = 13;
ptr = realloc(ptr, 2 * sizeof(int));
printf("%d %d\n", ptr[0], ptr[1]);
return 0;
}
Output:
4 13