#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;
}
OUTPUT:
Enter 5 numbers : 34
53
97
108
347
34 53 97 108 347
34 53 77 97 108
the value '347' is automatically getting replaced by '77'. When I input values >70, compiler replaces one of the values with 77 and displays it after sorting. And if I input values <70 then the program works fine. Can someone explain this please? And how to fix this?
This code block
if(*(p+i)>*(p+i+1))
{
temp=*(p+i);
*(p+i)=*(p+i+1);
*(p+i+1)=temp;
}
results in undefined behavior when i
is equal to 4
because the expression *(p+i+1)
accesses memory beyond the array.
Pay attention to that it is a bad design when functions depend on the magic number 4
.
For example the function sort
could be declared like
void sort( int *p, size_t n );
where the parameter n
specifies the number of elements in the pointed array.