/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
const int Success = 0, SizeZero = -1, NotMemory = -2, StartNewSize = 25, IncrementSizeBy = 10;
const int GetElementsSmallerThanNum(int source[], size_t sourcesize, int **dest, int Num);
void PrintElementsOf(int source[], int sourcesize);
int main (void)
{
int numbers[] = {45, 64, 1 ,4, 7, 0, -1, -35, 46, 53, 79, 65, -67, 0, 89, 24, 8, 88, 12, 342, 78, 96,
456, 765, 123, 98, 68, 798, 1234, 908, 5678
};
int *smallers = (int *)NULL, Limit = 55, result;
printf ("The list of numbers is:\n");
PrintElementsOf(numbers, sizeof(numbers) / sizeof(numbers[0]));
result = GetElementsSmallerThanNum(numbers, sizeof(numbers) / sizeof(numbers[0]), &smallers, Limit);
//here must be code checking for lack of memory -after all that is the only point of failure in this test-
printf ("The elements smaller than: %d are:\n", Limit);
PrintElementsOf(smallers, result);
return Success;
}
void PrintElementsOf(int source[], int sourcesize)
{
if (sourcesize <= 0)
printf("There is nothing to show");
else
for (int i = 0; i < sourcesize; ++i)
printf("%d ", source[i]);
printf("\n");
}
const int GetElementsSmallerThanNum(int source[], size_t sourcesize, int **dest, int Num)
{
if (sourcesize <= 0)
return SizeZero;
int destsize = (sourcesize / 2) + 1;
int *temp = (int *)malloc(destsize * sizeof(int));
if(temp == (int *)NULL)
return NotMemory;
int j = 0;
for (int i = 0; i < sourcesize; ++i)
{
if (source[i] < Num)
{
if(i == destsize)
{
destsize += IncrementSizeBy;
if(destsize > sourcesize)
destsize = sourcesize;
temp = (int *)realloc(temp, sizeof(int) * destsize);
if(temp == (int *)NULL)
{
free(temp);
return NotMemory;
}
}
temp[j++] = source[i];
}
}
if(j < destsize)
temp = (int *)realloc(temp, sizeof(int) * j);
*dest = temp;
return j;
}