Hello,
I have a problem when I try to double the length of the array if it is already full.

For example,
array arr has length 5, and I want to insert 7 elements in it.

This is what should I get:
arr = [1, 2, 3, 4, 5, 6, 7]
length of arr = 10;

This is what I am getting:
[1717986918, 1075603046, 3, 4, 5, 6, 7]
malloc: *** error for object 0x100180: double free

This is the function:

void double_array_1d(int* arr, int length) {

    int* temp_arr = new int[2 * length];
    for (int i = 0; i < length; i++) {
        temp_arr[i] = arr[i];
    }

    delete[] arr;
    arr = temp_arr;
}

Any help is appreciated, thanks.

Recommended Answers

All 2 Replies

The first parameter needs to be a reference or pointer to a pointer. All that function is doing now is changing its own local copy of the pointer.

Suggest either of these changes: void double_array_1d(int** arr, int length) or this void double_array_1d(int*& arr, int length) If you use the first form you will have to make a couple minor other changes *arr = temp; and temp_arr[i] = (*arr)[i];

Thanks for your help, that works

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.