0

I read the dynamic array and use it, but i have a bit question: When i put following format in prototype:

void mmyfunc(int *& myArray)
{
 //implementation
}

1.if i pass an array to it, how to call it? because i get :

no matching function for call to 

2.When i use the following implementation :

void NetworkSocket::resizeArray (int *&orig, int index, int size)
{
    int *resized =  new  int[size];
    for (int i = 0; i < size; i++)
    {
        if ( i == index )
            i++;

        resized[i] = orig[i];
    }
    delete [] orig;
    orig = (int *)new int[size];
    orig = resized;
}

i get seg fault in delete [] line.

2
  • 10
    How are you passing an "array" to it? Also, this code is leaks and segfaults all over: why go out of your way to get extra trouble? Use std::vector. Commented Jul 30, 2012 at 17:34
  • 1
    You left out the most important part of the code ... how you call it. Commented Jul 30, 2012 at 17:37

1 Answer 1

1

I'll just assume by array you mean

int x[16];

and you call the function as

resizeArray (x, ...)

So delete[]-ing it explicitly results in undefined behavior, because it wasn't allocated with new[]. Moreover, x resides in automatic memory, so it gets cleaned up by itself. Moreover moreover, you can't re-assign arrays. Arrays are not pointers. They decay to pointers when passed as arguments.

If you declared the array as

int* x = new int[16];

then your approach would work. But not quite C++ yet.

You can just use a std::vector and resize(). Don't re-invent the wheel (unless this is an assignment).

EDIT: Just spotted this:

orig = (int *)new int[size];
orig = resized;

will leak. Remove the extra new[].

EDIT 2:

What's

if ( i == index )
        i++;

supposed to do?

Sign up to request clarification or add additional context in comments.

3 Comments

I would have put the vector advice first, but that's just me.
@EtiennedeMartel could be for educational purposes.
"then your approach would work"... The general approach yes, but not the current implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.