Unexpected output while using Microsoft Visual Studio 2008 (Express Edition) C++ Command Line Tool

Posted by Sujith S Pillai on Stack Overflow See other posts from Stack Overflow or by Sujith S Pillai
Published on 2011-01-01T20:45:41Z Indexed on 2011/01/01 20:54 UTC
Read the original article Hit count: 129

Filed under:
|
|

One of my friends sent this code to me, saying it doesn't work as expected:



#include<stdio.h>

void main()
{

int a [10] ={23, 100, 20, 30, 25, 45, 40, 55, 43, 42};
int sizeOfInput = sizeof(a)/sizeof(int);
int b, outer, inner, c;
printf("Size is : %d \n", sizeOfInput);

printf("Values before bubble sort are  : \n");
for ( b = 0; b < sizeOfInput; b++)
    printf("%d\n", a[b]);

printf("End of values before bubble sort... \n");

for ( outer = sizeOfInput; outer > 0; outer-- )
{
    for (  inner = 0 ; inner < outer ; inner++)
    {
        printf ( "Comparing positions: %d and %d\n",inner,inner+1);
        if ( a[inner] > a[inner + 1] )
        {
            int tmp = a[inner];
            a[inner] = a [inner+1];
            a[inner+1] = tmp;
        }
    }
    printf ( "Bubble sort total array size after inner loop is %d :\n",sizeOfInput);
    printf ( "Bubble sort sizeOfInput after inner loop is %d :\n",sizeOfInput);

}
printf ( "Bubble sort total array size at the end is %d :\n",sizeOfInput);
for ( c = 0 ; c < sizeOfInput; c++)
    printf("Element: %d\n", a[c]);
}


I am using Micosoft Visual Studio Command Line Tool for compiling this on a Windows XP machine. cl /EHsc bubblesort01.c

My friend gets the correct output on a dinosaur machine (code is compiled using TCC there).
My output is unexpected. The array mysteriously grows in size, in between.

If you change the code so that the variable sizeOfInput is changed to sizeOfInputt, it gives the expected results!

A search done at Microsoft Visual C++ Developer Center doesn't give any results for "sizeOfInput".

I am not a C/C++ expert, and am curious to find out why this happens - any C/C++ experts who can "shed some light" on this?
Unrelated note: I seriously thought of rewriting the whole code to use quicksort or merge sort before posting it here. But, after all, it is not Stooge sort...

© Stack Overflow or respective owner

Related posts about c++

Related posts about c