+ 1
I need help with the output?
I'm making a linear search program in cpp, but when the user enters the target value, I get the correct information (found at index 0, for example) followed by (found at index(whatever the maximum index is)). can someone please help? https://code.sololearn.com/cTc1D1Qz8t30/?ref=app
1 Antwort
+ 2
sizeof(arr) returns the size of the array * the size of the data type.
The int in this case has a size of 4 so sizeof(arr) return 16
So you're gonna have undefined behaviour when you go up that high.
What you want to do is divide sizeof(arr) by sizeof(int) or sizeof(arr[0]) to end up with the correct size.
Also, you should break when you found the value.
Note that sizeof doesn't work correctly when used on an array that is allocated on the heap or an array used in a function parameter so it is best to store the size before allocating.