I’m trying to append two arrays together. The first array {0, 1, 2} when appended to the second array {3, 4, 5} should yield {0, 1, 2, 3, 4, 5}. Let me show you what I have before I move on:
#include <iostream>
int main() {
int i = 0;
int arr1[] = {3, 4, 5}, arr2[] = {0, 1, 2};
while (i < 3) {
arr2[3 + i] = arr1[i];
i++;
}
std::cout << std::endl;
for (int i = 0; i < 6; i++) std::cout << arr2[i] << std::endl; // print
}
I think the way I implemented it is correct. But I find that when I print out the contents of the new array (arr2) this is what I get:
0
1
2
-1219315227
-1218166796
134514640
0, 1, 2 is the original array, but then 3, 4, 5 has some how been turned into these weird numbers. However, this is somehow fixed with I add an arbitrary std::cout statement here in the while loop:
...
while (i < 3) {
std::cout << 5 << '\n'; // just a random #
arr2[3 + i] = arr1[i];
i++;
}
...
And I print the array once again and it works!:
5
0
1
2
3
4
5
My question is why is this working when I use a std::cout statement inside the while loop as opposed to not doing that, in which case it gives me those numbers?
EDIT:
So it turns out what I have here is undefined behavior. With that, my question still stands: why does my code work with an std::cout call inside the while loop?
You are going beyond the bounds of
arr2here:arr2has size 3. What you are doing is undefined behaviour. All observed behaviours are consistent with undefined behaviour.