[英]Garbage Result in my code
Hey guys so I was working on this code that finds the same numbers and display them and so far the result is just random numbers I need help. 大家好,所以我正在研究可找到相同数字并显示它们的代码,到目前为止,结果只是我需要帮助的随机数。
int main(void){
int arr[10] = {1, 2, 3, 4, 5, 4, 8 ,8, 9, 10};
int i;
int j;
int same[10];
int ctr = 0;
for(i = 0; i < 10; i++){
for(j = 10; j > 0;j--){
if(arr[i] == arr[j]){
same[ctr++] = arr[i];//store the similar numbers
}
}
}
for(i = 0; i < 10; i++){
printf("%d", same[i]);
}
getch();
return 0;}
You're contradicting yourself. 你自相矛盾。 For the same array, you're using two different indexing scheme!!
对于同一数组,您正在使用两个不同的索引方案!
0
to 9
0
到9
10
from 1
. 1
开始索引10
。 The inner loop indexing is off-by-one , thereby accessing out of bound memory, which is invalid . 内部循环索引是一对一的 ,从而访问了无效的绑定内存。 This causes undefined behavior .
这会导致不确定的行为 。
You need to make it 你需要做到
for(j = 9; j >= 0;j--)
After that, you're attempting to print the values of all elements in the same
array, whereas all ( or none ) the element values may not be assigned a value, actually. 之后,您尝试打印
same
数组中所有元素的值,而实际上( 可能没有 )为所有( 或无 )元素值分配值。 You left the automatic variable uninitialized, thereby containing indeterminate values. 您未对自动变量进行初始化,从而包含了不确定的值。 Since the variable has never its address taken, attempting to use the value will again cause UB.
由于该变量从未使用过其地址,因此尝试使用该值将再次导致UB。
That said, once a match is found, you can use continue
to jump to the outer loop. 就是说,一旦找到匹配项,就可以使用
continue
跳转到外部循环。
从9开始第二个循环( j
循环),然后转到0。
I ran your code on codechef compiler, it was giving a run time error. 我在codechef编译器上运行了您的代码,它给出了运行时错误。 Because in your ctr++ step , value of ctr exceeded the size of the array same[].
因为在您的ctr ++步骤中,ctr的值超出了数组same []的大小。
Moreover, in your code you are comparing one element with itself so every number will be printed in the list(since i==j may be a possible case) 而且,在您的代码中,您正在将一个元素与其自身进行比较,因此每个数字都将被打印在列表中(因为i == j可能是这种情况)
It will be better if you include a condition i!=j
with it or iterate j from i+1 to 9
so that no self comparisons are done. 如果包含条件
i!=j
或将j from i+1 to 9
迭代j from i+1 to 9
这样最好不进行自我比较,那会更好。 The following is a working snippet of the same code(your for loop) :- 以下是相同代码的工作片段(您的for循环):-
for(i = 0; i < 10; i++){
for(j = 10; j > 0;j--){
if(arr[i] == arr[j] && i!=j){
same[ctr] = arr[i];//store the similar numbers
ctr++;
cout<<ctr<<" ";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.