-5
  • C language
  • bubble sorting by using pointer
  • I am using CodeBlocks IDE

I am getting a problem that when I am giving inputs more than 55, it is giving me as output some random number, but only for largest (greater than 55).

#include<stdio.h>

#include<conio.h>


void input(int * p) {
  int i;
  printf("Enter 5 numbers");
  for (i = 0; i < 5; i++)
    scanf("%d", p + i);
}

void display(int * p) {
  int i;
  for (i = 0; i < 5; i++)
    printf("\n%d", *(p + i));
}

void sort(int * p) {
  int r, t, i;
  for (r = 0; r < 5; r++) {
    for (i = 0; i < 5 - r; i++) {
      if ( * (p + i) > * (p + i + 1)) {
        t = * (p + i);
        *(p + i) = * (p + i + 1);
        *(p + i + 1) = t;
      }
    }
  }
}
void main() {
  int a[5];
  input(a);
  display(a);
  sort(a);
  display(a);
  getch();
}

Input to above code :

Enter 5 numbers 2
43
65
12
5

Output :

2
43
65
12
5


2  
5
12
28
43
Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40

1 Answers1

1

In your sort function, the first run through the inner loop (ie. for r == 0) :

for (i = 0; i < 5 - r; i++) {

will iterate between i = 0 and i = 4 (included).

In the loop body, you check the value at index i against the value at index i + 1 :

  if ( * (p + i) > * (p + i + 1)) {

But when i = 4, that means i + 1 == 5. 5 is not a valid index in the provided array (which only holds 5 values, so index 4 is the last).

This means you invoke undefined behavior.

To fix it, simply do :

for (i = 0; i < 4 - r; i++) {
Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40