Date: Thu, 29 Feb 1996 22:31:20 -0700 From: Tony Jones <tony@rtd.com> To: questions@freebsd.org Subject: Re: C question: what is wrong with this code Message-ID: <199603010531.WAA17108@seagull.rtd.com>
next in thread | raw e-mail | index | archive | help
In article <Pine.BSF.3.91.960229164732.5332A-100000@lisa.rur.com> 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 <string.h> 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 <stdlib.h> #include <stdio.h> #include <string.h> #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); }
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199603010531.WAA17108>