0

// i really cant figure out what is wrong in this code, and i cant get the initial array values of zero.

#include <iostream>
int* create()

{
    int arr[5] = { 0,0,0,0,0 };
    return arr;
}
void disp(int arr[])
{
        for (int j = 0; j < 5; j++)
        {
            std::cout << arr[j];
        }
        std::cout << std::endl;
}


int main()
{
    int* mat = create();
    std::cout << mat[2] << std::endl;
    disp(mat);
}
//what it displays:
0
-858993460-858993460-858993460-8589934604
GuguWolf
  • 15
  • 3
  • that groovy number converts to hex as FFFFFFFDFFFFFFF4. Is it recognizable to you? – user4581301 Apr 28 '21 at 20:03
  • 6
    `arr` is local to the function, returning it is a bad idea, its lifetime ends as soon as the funcion returns. – anastaciu Apr 28 '21 at 20:04
  • 1
    An alternative is to declare the array in `create` as `static`. The `static` keyword will ensure that the array does not disappear after execution leaves the function. – Thomas Matthews Apr 28 '21 at 20:08

1 Answers1

-1

Your code fails to run for me. I got the warning "address of local variable ‘arr’ returned". When you are using array references like this, you should use dynamic arrays to avoid these kinds of errors. I changed arr accordingly and it works.

int* create()
{
    int * arr = new int[5] {0,0,0,0,0};
    return arr;
}

However, now arr will not get destructed when not being used anymore. If you are calling this creation function over and over, you should either create your own container that has a proper destructor, or use one of the modern containers provided by the standard library (std::vector, std::array).