简体   繁体   中英

Why does my same C code produce inconsistent results when compiling

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

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]

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.

给我同样的结果{-100,-5,0,1,2,6,10,12,23,24},您可能会得到奇怪的数字的原因是因为数组用完了索引,但是除非代码不变,不应该发生。

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