1

I tried to build a function that takes an array and its size and returns an array with only the even numbers from the first array.

#include <iostream>

using namespace std;

int noOdds(int v[], int dim)
{
    int vp[dim];

    for (int i = 0, k = 0; i < dim; i++)
    {
        if (v[i] % 2 == 0)
        {
            vp[k] = v[i];
            k++;
        }
    }
    return vp;
}

int main()
{
    int v1[3] = { 1,2,3 };

    cout << noOdds(v1, 3);
    return 0;
}

The error I am getting:

main.cpp: In function ‘int noOdds(int*, int)’:
main.cpp:21:12: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
   21 |     return vp;
      |            ^~
      |            |
      |            int*

I kept looking on the internet for different ways to solve this error, but I didn't find anything, I would be very grateful if someone could help me. Thank you!!

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
Alex Ciufu
  • 11
  • 2
  • Read about [array to pointer decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). The return type of the function is `int` but you're returning an `int*`. – Jason Nov 23 '22 at 13:13
  • 1
    Also `int vp[dim];` is not standard c++. See [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Jason Nov 23 '22 at 13:14
  • #1 `return vp;` your code attempts to return a pointer to the first element of the array since c++ you can't return a `c` style array. #2 your function is declared to return a single `int` and not an `int *` #3 if your function was declared to return `int*` that would not work either since the array `vp` no longer exists after the function ends. You can however return a single integer element from that array without issue. I hope this comment makes all the links more clear. They all explain different parts of the reason but for a new person this may not be all obvious. – drescherjm Nov 23 '22 at 14:32
  • 1
    Thank you for these comments, I also visited those links and with the gentleman's @ drescherjm comment I understood where I was wrong, thank you once again!! – Alex Ciufu Nov 23 '22 at 14:40
  • @JasonLiam Yes, I agree. KTGW – YSC Nov 23 '22 at 15:28
  • Hi! Use std::array! – Richard Bamford Nov 23 '22 at 18:15

0 Answers0