【发布时间】:2018-09-21 07:12:05
【问题描述】:
我的一个朋友将此代码发送给我,说它没有按预期工作:
#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]);
}
我正在使用 Micosoft Visual Studio 命令行工具在 Windows XP 机器上编译它。
cl /EHsc bubblesort01.c
我的朋友在恐龙机器上得到了正确的输出(代码在那里使用 TCC 编译)。
我的输出出乎意料。数组的大小在两者之间神秘地增长。
如果您更改代码以将变量sizeOfInput 更改为sizeOfInputt,它会给出预期的结果!
在Microsoft Visual C++ Developer Center 上进行的搜索没有给出“sizeOfInput”的任何结果。
我不是 C/C++ 专家,我很想知道为什么会发生这种情况 - 任何 C/C++ 专家可以对此有所了解吗?
无关说明:我认真考虑过重写整个代码以使用快速排序或合并排序,然后再将其发布到此处。但是,毕竟不是Stooge排序……
编辑:我知道代码不正确(它超出了最后一个元素),但我很好奇为什么变量名会有所不同。
【问题讨论】:
-
感谢您的编辑,但只是注意到它搞砸了 >和 < (>.
标签: c visual-studio-2008