Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 29 Feb 1996 18:34:17 -0500 (EST)
From:      Leo Papandreou <leo@rur.com>
To:        questions@FreeBSD.org
Subject:   Re: C question: what is wrong with this code
Message-ID:  <Pine.BSF.3.91.960229183114.8616B-100000@lisa.rur.com>
In-Reply-To: <Pine.BSF.3.91.960229164732.5332A-100000@lisa.rur.com>

next in thread | previous in thread | raw e-mail | index | archive | help


Never mind.

int	keycmp(const void *a, const void *b)
{
	return strcmp(*((char **)a), *((char **)b));
}

and in main()

...
	qsort(table, n, sizeof(char *), keycmp);
...

does the trick.


On Thu, 29 Feb 1996, Leo Papandreou wrote:

> 
> 
> I am having a problem with elementary C. The following stub
> reproduces the problem exactly. What am I doing wrong?
> 
> 
> #include	<stdlib.h>
> #include	<stdio.h>
> #include	<string.h>
> 
> #define	TABLESIZE	10
> #define	ITERATIONS	10
> 
> 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);
> 		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?Pine.BSF.3.91.960229183114.8616B-100000>