简体   繁体   English

为什么这个for循环无限循环? (C)

[英]Why is this for loop infinitely looping? (C)

This is really strange. 这真是奇怪。 This program was working fine on another computer, but when I try it on this one it runs forever. 该程序可以在另一台计算机上正常工作,但是当我在该计算机上尝试该程序时,它将永远运行。 Also it is a for loop, which adds even more to my confusion. 这也是一个for循环,这使我更加困惑。 SIZE_OF_DATA is a preprocessor variable, which I think might be causing the problem.. But I don't know. SIZE_OF_DATA是一个预处理器变量,我认为这可能是导致问题的原因。但是我不知道。 When I add a printf, it shows only one iteration of the outside loop and is looping infinitely in the inner loop. 当我添加一个printf时,它仅显示外部循环的一个迭代,并且在内部循环中无限循环。 I have no idea why. 我不知道为什么。

for(i=0; i<size; i++){
    for(j=0;j<SIZE_OF_DATA; j++){
      aArray[i*SIZE_OF_DATA + j] = aPointer[i]->b[j]; 
      cArray[i*SIZE_OF_DATA + j] = 0;                            
      dArray[i*SIZE_OF_DATA + j] = i*SIZE_OF_DATA + j;
      if (i==0)
        eArray[j] = 0;
    }
  }

I'm worried that I somehow destroyed my program... But I have barely done anything but add comments! 我担心我以某种方式破坏了我的程序……但是除了添加注释之外,我几乎什么都没做!

This: 这个:

aArray[i*SIZE_OF_DATA + j]

looks like you might be writing outside the array ( cArray and dArray too) in the last iteration. 您似乎阵列(外写cArraydArray太)在最后一次迭代。 Are you sure you're getting a correct index into the array? 您确定要在数组中获得正确的索引吗? If not, through the wonders of undefined behavior, you are probably writing to memory that belongs to other variables, including i and j , which could make this loop go on forever. 如果不是这样,那么通过未定义行为的奇迹,您可能正在写入属于其他变量(包括ij内存,这可能会使该循环永远持续下去。

Buggy programs with undefined behavior behave very... undefined. 具有未定义行为的Buggy程序的行为非常...未定义。 Though without seeing more code, no one can be sure. 尽管没有看到更多代码,但没人能确定。

My approach to debugging this piece of code would be to print the values i and j in the for loop. 我调试这段代码的方法是在for循环中打印值i和j。 Perhaps SIZE_OF_DATA increases unintentionally in some block of your code although this shouldn't matter. 也许SIZE_OF_DATA在您的某些代码段中无意中增加了,尽管这无关紧要。

尝试将i * SIZE_OF_DATA + j设置为变量,这可能就是您的问题所在。

Can you please mention the data type of 'j'. 能否请您提及“ j”的数据类型。 I assume that if suppose the data type of 'j' is char and your value of 'SIZE_OF_DATA' macro is some thing like 150. then the value of 'j' will be iterated between -128 to 127. So it will run infinitely 我假设如果'j'的数据类型为char并且您的'SIZE_OF_DATA'宏的值是150,那么'j'的值将在-128到127之间迭代。因此它将无限运行

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

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