0
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?

Austin
  • 6,921
  • 12
  • 73
  • 138
  • `newArray` has automatic storage duration and is destroyed when it goes out of scope, leaving a dangling pointer. – chris Jul 09 '15 at 02:40
  • How about googling? Btw. you´re missing a `delete[]`, your array with variable size is invalid, and a vector would make everything easier. – deviantfan Jul 09 '15 at 02:42
  • I know vectors are easier, but I have to learn it this way for class. The professor never mentioned anything about `new` but it was in the example answer. I did google it, but I didn't really understand. I was hoping I could get a simpler explanation. Honestly I'm not even sure why the other answer linked addresses this question. – Austin Jul 09 '15 at 02:45
  • 1
    @AustinMW, `new` dynamically allocates memory. It doesn't get cleaned up when the pointer goes out of scope (the pointer itself gets cleaned up instead). Therefore, you can return the pointer and it will still be valid. The other answer explains in detail why your version doesn't work. I will give you that it doesn't explain solutions such as `new` or (better) a container, but you have such a solution in your question. – chris Jul 09 '15 at 02:54
  • ahh, okay I'm starting to get it now, thanks. – Austin Jul 09 '15 at 02:56

0 Answers0