Lazar Šćekić
Lazar Šćekić

Reputation: 1

Array passing and returning

I was wondering.. Whenever I deal with arrays, when I have to cut it, or sort it, or anything, and then return it, I pass it to the void function like f(array, length, newarray) and in the function declaration I have void f(T *array, int length, T *&new array). Is there a better way to do this?

Here's some code, I want to remove repeats from an array:

template<class T>
void eliminate(T *niz, int duzina, T *&podniz)
{
    int ind;
    podniz = new T[duzina];
    for (int i = 0; i<duzina; i++)
    {
        ind = 0;
        for (int j = i; j<duzina; j++)
        {
            if (niz[i] == niz[j])ind++;
        }
        if (ind == 1)podniz[nova++] = niz[i];
    }
}

Upvotes: 0

Views: 86

Answers (2)

MSalters
MSalters

Reputation: 179779

As already noted in the comments, you really want std::vector.

The main problem with your code is that there is no way to tell how many of the output elements are actually initialized. And accessing uninitialized elements is Undefined Behavior, so you are returning a time bomb to the caller.

With std::vector<T> eliminate(std::vector const&), there's no such doubt. The returned vector has exactly .size() elements.

Vector is also exception-safe. Your code will leak memory if the copy constructor of T throws, e.g. on a std::bad_alloc.

Upvotes: 2

udbhateja
udbhateja

Reputation: 978

Sure. You can use pointers and pass the array by reference to the function. Then manipulate the array and return from the function with void type i.e no need of returning the array as it is passed by reference.

Upvotes: 0

Related Questions