简体   繁体   中英

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!!

  • In outer loop ( ascending index ), you're indexing from 0 to 9
  • In inner loop ( decending index ), you're indexing 10 from 1 .

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. 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.

That said, once a match is found, you can use continue to jump to the outer loop.

从9开始第二个循环( j循环),然后转到0。

I ran your code on codechef compiler, it was giving a run time error. Because in your ctr++ step , value of ctr exceeded the size of the array 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)

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. The following is a working snippet of the same code(your for loop) :-

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<<" ";
        }
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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