下面是利用时间做为随机数的种子生成一个数组,然后利用指针进行排序,结果出现了想不到的错误,错误的代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10
void sort(int *);
int main()
{
time_t ts; //时间数据类型
unsigned int num = time(&ts); //获取时间,转换为整数
srand(num); //初始化随机种子
int a[N];
for(int i=0;i<N;i++)
{
a[i] = rand() % 100;
printf("%d\t%d\n",i,a[i]);
}
sort(a);
printf("排序后的数据:\n") ;
for(int j=0;j<N;j++)
{
printf("%d\t%d\n",j,a[j]);
}
system("pause");
}
void sort(int a[])
{
int * temp;
for(int i=0;i<N-1;i++)
{
a[i];
for(int j=0;j<N-i;j++)
{
if(*(a+j) > *(a+j+1))
{
temp = &a[j];
<span style="white-space:pre"> </span>*temp = *(a+j);
*(a+j) = *(a+j+1);
*(a+j+1) = temp;
}
}
}
}
而上面的代码错误出现在:
void sort(int a[])
{
int * temp;
for(int i=0;i<N-1;i++)
{
a[i];
for(int j=0;j<N-i;j++)
{
if(*(a+j) > *(a+j+1))
{
temp = &a[j];
*temp = *(a+j);
*(a+j) = *(a+j+1);
*(a+j+1) = temp;
}
}
}
}
正确的应该代码:
void sort(int a[])
{
int temp;
for(int i=0;i<N-1;i++)
{
a[i];
for(int j=0;j<N-i;j++)
{
if(*(a+j) > *(a+j+1))
{
temp = *(a+j);
*(a+j) = *(a+j+1);
*(a+j+1) = temp;
}
}
}
}