A
A
Anatoly Ivanov2016-11-22 17:48:40
C++ / C#
Anatoly Ivanov, 2016-11-22 17:48:40

Why does this code return such a strange response?

Here is a piece of C code

int getMin(int numbers[], int size);

int main(){
    
    int numbers[10] = {0, 2, 4, 6, 1, 3, 8, 7, 9, 5};
    
    int res = getMin(numbers, 10);
    
    printf("%d\n", res);
}

int getMin(int numbers[], int size){
    
    int key;
    int min = numbers[0];
    
    for(int i = 0; i < size; i++){
        
        if(min > numbers[i]){
            min = numbers[i];
            key = i;
        }
        
    }
    
    return key;
}

Why is the answer != 0 ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Antony, 2016-11-22
@apeks

Learn to use the debugger and see for yourself what you get back from where and where these values ​​come from. Well, look where your program goes (or does not go) and why.
По-тому, что значение key не определено, и при заданном начальном массиве оно не будет изменено. Т.е. ваша функция, если первый элемент массива минимален, будет возвращать условно случайное значение.

V
Vasily Melnikov, 2016-12-01
@BacCM

Just without a debugger in mind, "execute" your program and see that you never hit the if body

S
Sh0ttky, 2016-12-01
@Sh0ttky

if(min > numbers[i]){
            min = numbers[i];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question