Among the problems in the posted code:
- Indexing is incorrectly 1-based. C is a zero-based indexing system. An array of 20 elements is indexed using
[0] through [19].
- Arbitrary function argument declarations. In C,
int foo(); declares a function called foo that returns int and takes an arbitrary list. Therefore, foo(), foo(1), foo(1,2,3), foo("grandma's house", 3.14), all are compliant. Your function declaration should prototype exactly what you're expecting. In this case, void sort(int a[], int len);
- Improper pointer indirection. Your sort function should take a pointer and length as arguments. As discussed before, however, your declaration argument list is arbitrary, and your implementation actually takes a pointer-to-pointer (
int *a[], which is equivalent to int **a).
- Check your IO input operations. Validate your input operations. Don't assume they work. Assumption is the mother of all...
- Boundary checks. Make sure you never overrun your array boundaries by verifying the input data won't allow that to happen in the first place.
Each of these issues, and more, is addressed below:
#include <stdio.h>
#include <stdlib.h>
void sort(int a[], int len);
void sp(int *l, int *m);
int main()
{
int x, v[20];
if (scanf("%d", &x) == 1 && x > 0 && x <= 20)
{
for (int i = 0; i < x;)
{
// prompt for input
printf("a[%d] :", i);
fflush(stdout);
// try to read next element
if (scanf("%d", v + i) != 1)
{
// failed to read. clear stdin through newline
int c;
do {
c = fgetc(stdin);
} while (c != EOF && c != '\n');
// if we actually hit EOF, stop reading and
// reset x to however many items we read well.
if (c == EOF)
{
x = i;
break;
}
continue;
}
// read successful, move to next element
++i;
}
for (int i = 0; i < x; ++i)
printf("%d ", v[i]);
fputc('\n', stdout);
sort(v, x);
for (int i = 0; i < x; ++i)
printf("%d ", v[i]);
fputc('\n', stdout);
}
return 0;
}
void sort(int a[], int len)
{
if (len <= 1)
return;
int swapped = 1;
while (swapped && len-- > 0)
{
swapped = 0;
for (int i = 0; i < len; ++i)
{
if (a[i + 1] < a[i])
{
sp(a + i, a + i + 1);
swapped = 1;
}
}
}
}
void sp(int *l, int *m)
{
int n = *l;
*l = *m;
*m = n;
}
sortand arguments passed to thereof. And whatever tutorial is telling you to declare arbitrary argument list function decls should really be replaced with something from the last decade or two. Finally, bothsortandspclaim to returnint, then fail to deliver on that promise. Not that anyone is using that result anyway.spfunction, assuming the return type is changed tovoid(since it doesn't actually return anything).