冒泡排序用我什至没有输入的另一个值替换一个值

Bubble sort replacing a value with another one that I haven't even input

#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指定指向数组中元素的个数。