using realloc for a dynamically growing array
Hi, I'm trying to write a program that will create a dynamically growing array. There is a parent array and from this I want to create a seperate array with elements that are less than <= 166 (some random number). For some reason, this code is working for smaller values like 5 or 6 but failed when i entered parent_size = 23.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *parent;
int *child = NULL, *tempstore;
size_t child_size, i, parent_size;
printf("Enter size of parent array\n");
if(scanf("%d", &parent_size) != 1)
return (1);
parent = malloc(sizeof(int) * parent_size);
if(parent == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
for(i = 0; i < parent_size; i++)
{
printf("Enter element %d:", i);
if(scanf("%d", &parent[i]) != 1)
return (1);
printf("\n");
}
child_size = 0;
for(i = 0; i < parent_size; i++)
{
if(parent[i] <= 166)
{
tempstore = realloc(child, ++child_size);
if(tempstore == NULL)
{
fprintf(stderr, "Memory reallocation failed\n");
return (1);
}
tempstore[child_size - 1] = parent[i];
child = tempstore;
}
}
for(i = 0; i < child_size; i++)
printf("%d\n", child[i]);
return (0);
}