0

I want to add one more value into C++ array, and I have this piece of code:

void print_array(int *array, int size)
{
    for (int i = 0; i < size; ++i)
    {
        std::cout << array[i] << ' ';
    }
    std::cout << '\n';
}

void add_to_array(int *array, int size, int value)
{
    int *newArr = new int[size + 1];
    memcpy(newArr, array, size * sizeof(int));
    delete[] array;
    array = newArr;
    array[size + 1] = value;
}

int main(int argc, char const *argv[])
{
    int *array = new int[10];
    array[0] = 0;
    array[1] = 1;
    array[2] = 2;
    array[3] = 3;
    array[4] = 4;
    array[5] = 5;
    array[6] = 6;
    array[7] = 7;
    array[8] = 8;
    array[9] = 9;
    print_array(array, 10);
    add_to_array(array, 10, 11);
    print_array(array, 11);
}

I dont get any errors when I run it but the output is very wierd:

0 1 2 3 4 5 6 7 8 9 
0 0 -307888112 32767 4 5 6 7 8 9 1041

Any ideas how can I do it properly?

I know about vectors on lists in stl but i cannot use them so dont suggest it

1
  • 2
    Rather use a std::vector<int> array(10); and push_back() to add elements at the end. Commented Oct 25, 2020 at 13:44

1 Answer 1

5

Function arguments of C++ are copies of what are passed and changing them won't affect what are passed. You should use references to have functions change what are passed.

Also note that now the new array has size + 1 elements and the index of the last element is size, not size + 1.

Fixed code:

void add_to_array(int *&array, int size, int value) // add & to make "array" a reference
{
    int *newArr = new int[size + 1];
    memcpy(newArr, array, size * sizeof(int));
    delete[] array;
    array = newArr;
    array[size] = value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's better for sure but when im printing second time the value at 10th place is 0 and not the pessed value into the function. I can change it in main. How can repair this?
@F.Hand Fix the index for new element.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.