Skip to content

Instantly share code, notes, and snippets.

@sgeos
Last active July 8, 2023 06:37
Show Gist options
  • Save sgeos/a3fa4f5bd1f21b2cdce9367fb05ad281 to your computer and use it in GitHub Desktop.
Save sgeos/a3fa4f5bd1f21b2cdce9367fb05ad281 to your computer and use it in GitHub Desktop.
C qsort example. It takes a list of values from the command line and sorts them in ascending order.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
void usage(const char *pProgramName) {
printf("Usage: %s x y z ...\n", pProgramName);
printf("Example: %s 818 -3 566 5 12 100 12 25\n", pProgramName);
printf(" This program will sort numbers in ascending order.\n");
}
/***
* Input: argc, argv, an optional array, and the array length
* Output: total number of scanned items
*
* All scanned items are stored in the array if it is supplied.
* This function can be run once to get the length of the array,
* and a second time to actually populate the array.
*/
size_t parse_args(int argc, const char *argv[], int *pArray, size_t pLength) {
size_t index = 0;
// skip arv[0]
for (int i = 1; i < argc; i++) {
int value_scanned;
int items_scanned = sscanf(argv[i], "%d", &value_scanned);
if (NULL != pArray && index < pLength) {
pArray[index] = value_scanned;
}
// EOF is negative
if (0 < items_scanned) {
index += items_scanned;
}
}
// final index is the total number of scanned items
return index;
}
void print_array(int *pArray, size_t pLength) {
int i;
for (i = 0 ; i < pLength - 1; i++) {
printf("%d ", pArray[i]);
}
printf("%d\n", pArray[i]);
}
int qsort_compare(const void *pA, const void *pB) {
return (*(int*)pA - *(int*)pB);
}
int main (int argc, const char *argv[]) {
size_t length = parse_args(argc, argv, NULL, 0);
int array[length];
parse_args(argc, argv, array, length);
if (length < 1) {
usage(argv[0]);
return 1;
} else {
qsort(array, length, sizeof(int), qsort_compare);
print_array(array, length);
}
return 0;
}
qsort_ascending: qsort_ascending.c
$(CC) -o $@ $^
test: qsort_ascending
./qsort_ascending || true # pipe to ignore error
./qsort_ascending 818 -3 566 5 12 100 12 25
./qsort_ascending 0
./qsort_ascending 1 -1 0 0 0 0 0
.PHONY: clean
clean:
rm -f *.o *~ core qsort_ascending
@sgeos
Copy link
Author

sgeos commented Jul 8, 2023

Although this is a qsort() example, the parse_args() function took the most time to get right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment