From owner-freebsd-questions Thu Feb 29 21:31:26 1996 Return-Path: owner-questions Received: (from root@localhost) by freefall.freebsd.org (8.7.3/8.7.3) id VAA16403 for questions-outgoing; Thu, 29 Feb 1996 21:31:26 -0800 (PST) Received: from seagull.rtd.com (root@[198.102.68.2]) by freefall.freebsd.org (8.7.3/8.7.3) with SMTP id VAA16398 for ; Thu, 29 Feb 1996 21:31:24 -0800 (PST) Received: (from tony@localhost) by seagull.rtd.com (8.6.12/1.2) id WAA17108 for questions@freebsd.org; Thu, 29 Feb 1996 22:31:20 -0700 Date: Thu, 29 Feb 1996 22:31:20 -0700 From: Tony Jones Message-Id: <199603010531.WAA17108@seagull.rtd.com> To: questions@freebsd.org Subject: Re: C question: what is wrong with this code Newsgroups: rtd.freebsd.questions Organization: RTD Internet Access X-Newsreader: TIN [version 1.2 PL2] Sender: owner-questions@freebsd.org Precedence: bulk In article you wrote: : I am having a problem with elementary C. The following stub : reproduces the problem exactly. What am I doing wrong? I'm not even going to ask why you are using char arrays rather than ints :-) 1) comparing integers lexically won't work 3468 is lexically < 400 #include main() { printf("%d\n", strcmp("3468", "400")); } zebedee:12% ./a.out -1 2) From the man page: >The contents of the array base are sorted in ascending order according to >a comparison function pointed to by compar, which requires two arguments >pointing to the objects being compared. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If your array was made of int's, the comparison function would receive int*. In your case, the arguments are char**, since your array contains elements of type char *. tony #include #include #include #define TABLESIZE 10 #define ITERATIONS 10 int f(const void *p1, const void *p2) { int a1 = atoi(*(char **)p1), a2 = atoi(*(char **)p2); if (a1 == a2) return 0; else return a1 < a2 ? -1 : 1; } main() { int i, j , n; char *table[TABLESIZE], buff[1024]; for (i = 0; i < ITERATIONS; i++) { /* * populate the table with some random strings */ n = random() % TABLESIZE + 1; for (j = 0; j < n; j++) { sprintf(buff, "%d", random() % 10000); table[j] = strdup(buff); } for (j = 0; j < n; j++) printf("%s\t", table[j]); printf("\n"); /* so far, so good. Now sort the table */ /* qsort(table, n, sizeof(char *), strcmp); */ qsort((void *)table, n, sizeof(char *), f); for (j = 0; j < n; j++) printf("%s\t", table[j]); printf("\n"); /* huh!? Doesnt look sorted, does it? */ for (j = 0; j < n; j++) free(table[j]); } exit(0); }