简体   繁体   English

嵌套的循环值未初始化

[英]nested for loop value of not initialized

I know question sounds dumb, I can't really figure out what is wrong in this code? 我知道问题听起来很愚蠢,我真的无法弄清楚这段代码有什么问题吗?

void sort(int *arr, int size)
{
    int min = 0;
    for (int i = 0; i < size - 1; i++)
    {
        for (int j = i; i < size; j++)
        {
            if (arr[min] > arr[j])
            {
                min = j;
            }
        }
        if (min != i)
        {
            Swap(&arr[i], &arr[min]);
        }
    }    
}

The following code should sort the arr but it is giving segmentation fault. 以下代码应该对arr排序,但它给出了分段错误。 I ran this code via debugger and it says the value of j at line 我通过调试器运行了这段代码,它在行中表示j的值

        for (int j = i; i < size; j++)

something like 3234 (not initialized) and program ends. 类似于3234 (未初始化)的内容,程序结束。 But j should be 0 . 但是j应该是0

debuger screenshort 调试器屏幕短

在第二个for循环中,它应该是j < size ,而不是i < size

There are 3 problems in your sort function: 您的sort功能中存在3个问题:

  • The test in the inner for loop uses i instead of j . 内部for循环中的测试使用i而不是j j is initialized but the test always succeeds and the loop goes on, letting the code access arr beyond its boundaries, causing undefined behavior. j已初始化,但测试始终成功,并且循环继续进行,使代码无法超出其边界访问arr ,从而导致未定义的行为。
  • min should initialized to i inside the outer loop, min应该在外循环内初始化为i
  • j should be initialized to i + 1 is the inner loop (minor). j应该初始化为i + 1是内部循环(次要)。

Here is a corrected version: 这是更正的版本:

void sort(int *arr, int size) {
    for (int i = 0; i < size - 1; i++) {
        int min = i;
        for (int j = i + 1; j < size; j++) {
            if (arr[min] > arr[j]) {
                min = j;
            }
        }
        if (min != i) {
            Swap(&arr[i], &arr[min]);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM