Im a newbie to "C" , I primarily migrated/re-implemeted "C" programs to Java, etc. I'm trying to learn "C" and I have gone through several tutorials. I have a program that attempts to read user input(numbers) from command line via "char *argv" , and sort those numbers & just print the sorted numbers out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
//if thee is argument supplied
if (argc > 1)
{
int count = 0;
//array to sort less 1
count = argc -1;
int tobe_sorted[count];
int i=0;
//allocate memory for target result array
int *target = malloc(count * sizeof(int));
//copy unsorted ints to target
memcpy(target, tobe_sorted, count * sizeof(int));
//sort target using bubble sort
int temp =0;
int x =0;
int y=0;
for (x=0; x<count; x++ )
{
for (y=0; y<count -1; y++ )
{
if (target[i]>target[i+1])
{
temp = target[i+1];
target[i+1] = target[i];
target[i] = temp;
}
}//end inner
}//end outer
//end bubble sort
x=0;
printf("Sorted:\n");
//print sorted array
while (x <count)
{
printf("%d",target[x]);
printf(",");
x++;
}
printf("\n");
}//end argument supplied
else{
printf("Error, please enter numbers to be sorted\n");
}
return 0;
}//end main function
My input :
PS C:\Users\xyz\workspace_cpp\the_hard_way\ex18> .\sort_test.exe 5 4 3 2 1
Output:
Sorted: 2686748,1986196690,32,1,4199492,
1) I'm not sure what "C" is printing out, are these ASCII codes? 2)What do I need to fix in the above program in order to print the sorted int array?
Disclaimer (Im not looking to use library functions such as qsort(), or to make the program more efficient).
Thanks a million!
Aucun commentaire:
Enregistrer un commentaire