Reputation: 9
I have written some sorting algorithm. For the sake of simplicity I have chosen a small array with unique values. Whenever I compile the code some times I get the correct answer but, sometimes I am getting a different answer with an error. I want to know what is causing the problem. Mind you I am using the same code.
I am using GCC 4.2.1
I have tried on an online compiler it is giving the correct answer.
#include <stdio.h>
int main(){
int i,j,k,l;
int A[10]={2,10,6,24,1,-5,23,0,12,-100};
for(i=0;i<10;i++){
if(A[i+1]<A[i]){
l=A[i+1];
for(j=0;j<=i;j++){
if((A[j]<A[i+1])&&(A[j+1]>A[i+1])){
for(k=i;k>=j;k--){
A[k+1]=A[k];
}
A[j+1]=l;
}
else if(A[0]>A[i+1]){
for(k=i;k>=0;k--){
A[k+1]=A[k];
}
A[0]=l;
}
}
}
}
for(i=0;i<10;i++){
printf("%d\n",A[i]);
}
}
sometimes it gives: { -100, -5, 0, 1, 2, 6, 10, 12, 23, 24, } Sometime it gives: -791216026, -100, -5, 0, 1, 2, 6, 10, 12, 23, Abort trap: 6
Upvotes: 1
Views: 399
Reputation: 70204
You program reads past the array.
When i
equals 9
, A[j+1]
reads past the array when i == j
which is allowed by your for(j=0;j<=i;j++)
loop stop condition.
This also applies to A[k+1]
Upvotes: 1
Reputation: 1458
It's not about your compilation. It may happen if you run the same file multiple time.
since you are accessing A[10] which does not contain a specific value, your program could behave in different ways, if the value in A[10] is greater than 24, that value remains in its position and correct response will print out, otherwise, it will propagate to somewhere between your numbers. so you loos your last number (24) and a random value goes inside your array.
Upvotes: 0