问题描述
#include<stdio.h>
//input function taking inputs from the user.
void input(int *p)
{
int i;
printf("Enter 5 numbers : ");
for(i=0; i<=4; i++)
{
scanf("%d",p+i);
}
}
//display function used to display values of the array.
void display(int *p)
{
int i;
for(i=0; i<=4; i++)
{
printf("%d\t",*(p+i));
}
printf("\n");
}
//Bubble Sort
void sort(int *p)
{
int rounds,temp,i;
for(rounds=1; rounds<=4; rounds++)
{
for(i=0; i<=4; i++)
{
if(*(p+i)>*(p+i+1))
{
temp=*(p+i);
*(p+i)=*(p+i+1);
*(p+i+1)=temp;
}
}
}
}
//Main Function calling other functions of the program
int main()
{
int a[5];
input(a);
display(a);
sort(a);
display(a);
getch();
return 0;
}
输出:
Enter 5 numbers : 34
53
97
108
347
34 53 97 108 347
34 53 77 97 108
值“ 347”将自动替换为“ 77”。当我输入> 70的值时,编译器将其中一个值替换为77,并在排序后显示。如果我输入的值小于70,则程序运行正常。有人可以解释一下吗?以及如何解决这个问题?
解决方法
当i
= 4时,您将比较p[4]
和p[5]
,并可能进行交换。
此代码块
if(*(p+i)>*(p+i+1))
{
temp=*(p+i);
*(p+i)=*(p+i+1);
*(p+i+1)=temp;
}
当i
等于4
时会导致未定义的行为,因为表达式*(p+i+1)
访问数组之外的内存。
请注意,当函数依赖于幻数4
时,这是一个糟糕的设计。
例如,函数sort
可以这样声明:
void sort( int *p,size_t n );
其中参数n
指定指向数组中的元素数。