It's quite interesting what is happening here and I would like to know why. After the recursion is ran 10 times, the *array = x and I have no idea why. I only want the program to return if when the element in the array is equal to x. However, when the userInput is equal to 2 or 3 or 4, the recursion is ran 10 times, *array = x, and the function returns. Any suggestions why this happening and how to fix it?
The array doesn't contain 2, 3 or 4 so the recursion never stops. It just keeps going, accessing memory outside the array, which will eventually lead to a program crash if the value you are looking for is not found.
I see, but what's weird is that the array after the last array is automatically set to equal to x.
array is: 5
x is: 1
array is: 6
x is: 1
array is: 7
x is: 1
array is: 8
x is: 1
array is: 9
x is: 1
array is: 10
x is: 1
array is: 11
x is: 1
array is: 12
x is: 1
array is: 13
x is: 1
array is: 14
x is: 1
array is: 1
x is: 1
Maybe the data stored right after the array happens to represent the int value 1. It's just pure coincidence. You should not rely on this behaviour. The C++ standard simply says the behaviour is undefined in this situation which means anything is allowed to happen. What you should do is to avoid accessing elements outside the array in the first place.
Maybe the data stored right after the array happens to represent the int value 1. It's just pure coincidence. You should not rely on this behaviour. The C++ standard simply says the behaviour is undefined in this situation which means anything is allowed to happen. What you should do is to avoid accessing elements outside the array in the first place.
This can't be a coincidence. I just ran the program, and no matter what value of x I input, the last recursion always sets the *array equal to x.
array is: 5
x is: 1
array is: 6
x is: 1
array is: 7
x is: 1
array is: 8
x is: 1
array is: 9
x is: 1
array is: 10
x is: 1
array is: 11
x is: 1
array is: 12
x is: 1
array is: 13
x is: 1
array is: 14
x is: 1
array is: 4196950
x is: 1
array is: 0
x is: 1
array is: 0
x is: 1
array is: 0
x is: 1
array is: 0
x is: 1
array is: 0
x is: 1
array is: 4196950
x is: 1
array is: 0
x is: 1
array is: -386274491
x is: 1
array is: 26537
x is: 1
array is: 0
x is: 1
array is: 0
x is: 1
array is: 1940665048
x is: 1
array is: 30172
x is: 1
array is: 0
x is: 1
array is: 1
x is: 1
It's going in!