Tim Tim - 1 month ago 4
C Question

What's wrong with this C program?I's always appear a new number we not input?Compiled with Dev-C++

enter image description here

This program is used to sort numbers #### min to max



When I input
5 1 3 7 9 6 8 2 0 4


the result is
0 1 2 3 3 4 5 6 7 8


the
9
disappeared and appeared another
3
that we did not input.

When I input
99 88 77 66 55 44 33 22 11 0


the result is
0 3 11 22 33 44 55 66 77 88


the
99
disappeared and appeared a
3
that we did not input. What's wrong?

#include<stdio.h>

void sort(int b[]){
for(int i = 0;i<10;i++){
for(int j = 0;j<10-i;j++){
if(b[j+1]<b[j]){
int temp = 0;
temp = b[j+1];
b[j+1] = b[j];
b[j] = temp;
}
}
}
}

void main(){
int a[10];
printf("please enter numbers you want to sort:\n");
for(int i = 0;i<10;i++){
scanf("%d",&a[i]);
}
printf("The number you have input were:");
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
sort(a);
printf("The sorted numbers are:");
for(int i=0;i<10;i++){
printf("%d ",a[i]);
}
}

Answer

You've got some undefined behavior here: b[j+1] for j=9 occurences you're accessing outside of the bounds (effectively b[10] which is the 11th element of b, but it contains only 10 elements) of your array.

When you have behavior like that, what'll happen is completly unpredictable. It may work. It may produce garbage values (like it did for you). On another try, your program might crash with a segfault.

Comments