int main()
{
int e[]={3,5,1,2,-2,-1,7,8,0,9};
int *f;
int fsize;
f=smaller_than(e,10,fsize,5);
}
I have a function:
int * smaller_than(const int list[],const int SIZE,int& count,const int THRESHOLD=0)
{
count = 0;
for (int i = 0; i < SIZE; i++)
{
if (list[i] < THRESHOLD)
{
count++;
}
}
int newArray[count];
int *p = newArray;
int j = 0;
for (int i = 0; i < SIZE; i++)
{
if (list[i] < THRESHOLD)
{
newArray[j] = list[i];
j++;
}
}
return p;
Which does not print correctly using a separate printing function, it prints 3 32767 229810164 1 -1 0
, but when I copy what another person did:
int * newArray = new int[count];
int j = 0;
for (int i = 0; i < SIZE; i++)
{
if (list[i] < THRESHOLD)
{
newArray[j] = list[i];
j++;
}
}
return newArray;
}
this works and prints 3 1 2 -2 -1 0
. I don't understand, why didn't mine work properly and what's the difference with using the "new" keyword?