I am a not a professional so please, bear with me.
I am in the process of learning C, and for practice I made a small program that reads a couple of numbers from argv
, and sorts them in ascending order.
So far it works pretty well. Except for 2 things:
- The program adds an extra zero to the list (I know why this is happening, but don't feel like fixing it right now)
- The biggest number somehow turns into a zero in the process (I don't know why this is happening and I want to fix it)
I am specifically concerned with Issue #2.
For example, when running ./a.out 6 8 4 9 3
the output comes out to 0 0 3 4 6 8
instead of 0 3 4 6 8 9
(once again I'm only concerned with the disappearance of the 9)
I am using gcc version 7.3.1 on Linux if it helps.
Why does the biggest number turn into a zero?
The code:
#include <stdio.h>
#include <stdlib.h>
void flip(short position, short * values){
int key = values[position];
values[position] = values[position + 1];
values[position + 1] = key;
}
void sort(short * values, short argc){
for( short iterations = argc; iterations > 0; --iterations){
for( short position = 1; position < iterations; ++position){
if (values[position] > values[position + 1])
flip(position, values);
}
}
for ( short i = 0; i < argc; ++i )
printf("%d ", values[i]);
printf("\n");
}
int main(short argc, char **argv){
if ( argc <= 1 ){
fprintf( stderr, "USAGE: %s <<short int>...>\n", argv[0] );
return 1;
}
short *values = malloc(sizeof(short) * (argc-1));
for (int i = 1; i < argc; ++i ){
values[i] = strtol(argv[i], NULL, 0);
}
sort(values, argc);
return 0;
}
Any help would very much be appreciated.
Edit: Having had run it through GDB I figured out that the issue is in not in the main function, as x/6uh values
still returns the correct values when sort
starts. The issue occurs while I am inside flip
. Still not sure what the problem is though...