Reputation: 53
I'm compiling the following code in my m/c using codeblocks and mingw32-gcc.exe v.4.8.1(tdm-2).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[8] = {3,1,10,-1,7,2,-8,1};
int b[8] = {3,1,10,-1,7,2,-8,1};
int i=0,alength = (int)sizeof(a)/sizeof(a[0]);
for(i = 0; i < alength; i++){
if(a[i] > a[i+1]){
a[i+1] = a[i] + a[i+1];
a[i] = a[i+1] - a[i];
a[i+1] = a[i+1] - a[i];
}
}
printf("Original array size is %d \n", alength);
printf("Original array elements are given below: \n");
printf("Sizeof(a) is %d \n", sizeof(a));
for(i = 0; i < alength; i++){
printf("\n b[%d] = %d", i, b[i]);
}
for(i = 0; i < alength; i++){
printf("\na[%d] = %d", i, a[i]);
}
}
It's giving me the following output. Here for each array, two extra elements are being printed.
Original array size is 10
Original array elements are given below:
Sizeof(a) is 32
b[0] = 3
b[1] = 1
b[2] = 10
b[3] = -1
b[4] = 7
b[5] = 2
b[6] = -8
b[7] = 1
b[8] = 1
b[9] = 3
a[0] = 1
a[1] = 3
a[2] = -1
a[3] = 7
a[4] = 2
a[5] = -8
a[6] = 1
a[7] = 8
a[8] = 10
a[9] = 9
But compiling the same code in online compiler gives the correct output. OS is Win8 64bit. Any help in explaining and resolving the difference would be appreciated..
Upvotes: 1
Views: 78
Reputation: 106092
Accessing out of bound array element invokes undefined behavior and this will result in any expected or unexpected result.
Change
for(i = 0; i < alength; i++){
if(a[i] > a[i+1]){ ...
...
}
to
for(i = 0; i < alength-1; i++){
if(a[i] > a[i+1]){ ...
...
}
Upvotes: 5
Reputation: 67439
What you have is the very definition of undefined behaviour, specifically the one pass bubble sort you're trying to write. i
goes from 0
to alength-1
, covering the entire array, then you index a[i+1]
, which is going to be past the end.
If I had to guess specifically what's causing the difference, one machine is building in debug mode introducing a sentinel between a
and b
, so in one instance you're comparing a[7]
with either b[0]
(going to swap) or with a[8]
(the sentinel, which is usually a large number so not going to swap).
TL;DR: Undefined behaviour.
Upvotes: 4