[英]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
。
在第二个for
循环中,它应该是j < size
,而不是i < size
。
There are 3 problems in your sort
function: 您的
sort
功能中存在3个问题:
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.