我在这里有一个整数数组排序程序,但我有一个问题:每当我运行程序时,我有时会得到一个“堆栈周围的变量'数字'已损坏'的消息,有时它只是反复打印出数字8。我的代码(在Visual C++ 2010编译):为什么不是这个代码打印我的数组?
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
void swap(int *x, int *y)
{
int tmp=0;
tmp = *x;
*x = *y;
*y = tmp;
tmp = 0;
}
int main()
{
int numbers[13] = {8,16,23,487,2,301,48,0,13,10,644,12};
int size = sizeof(numbers)/sizeof(int);
//sort
int i = 0;
int* a = &numbers[0];
int* b = &numbers[1];
while(i < size){
if(*a > *b){
swap(a, b);
}
*a++;
*b++;
i++;
}
//Print our results
int loopIterator = 0;
int numToPrint = 0;
while(loopIterator < size){
cout << numbers[numToPrint] << endl;
loopIterator++;
}
system("PAUSE");
}
and the Lord said:should integers always be 4 ... * sigh *,use sizeof(int)。 –
'int size = sizeof(numbers)/ sizeof(int);' – KevinDTimm
上述两种解决方案都不是最理想的。更好:'size_t size = sizeof numbers/sizeof numbers [0];' –