F.Hand
F.Hand

Reputation: 83

Adding one value at the end of c++ array

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

Upvotes: 0

Views: 2306

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

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;
}

Upvotes: 5

Related Questions