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
std::vector<int> array(10);andpush_back()to add elements at the end.