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:
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...
Your main problem is that you need to store the values in the array starting at values[0]
, and you mistakenly call your sort routine with argc which is too big. Try something like this:
#include <stdio.h>
#include <stdlib.h>
void flip(int position, int * values){
int key = values[position];
values[position] = values[position + 1];
values[position + 1] = key;
}
void sort(int * values, int numvals){
for( int iterations = numvals - 1; iterations >= 0; --iterations){ //TODO
for( int position = 0; position < iterations; ++position){
if (values[position] > values[position + 1])
flip(position, values);
}
}
for ( int i = 0; i < numvals; ++i )
printf("%d ", values[i]);
printf("\n");
}
int main(int argc, char **argv){
if ( argc <= 1 ){
puts("Did not specify any arguments. Exiting...");
return 1;
}
int *values = malloc(sizeof(int) * (argc-1));
for (int i = 1; i < argc; ++i ){
values[i-1] = strtol(argv[i], NULL, 0);
}
sort(values, argc - 1);
return 0;
}
I changed your shorts to ints, but that likely doesn't matter except for argc.