INFO: Sorting Structures with the C qsort() Function

만료된 KB 콘텐츠 고지 사항

이 문서는 Microsoft에서 더 이상 지원하지 않는 제품에 대해 작성되었습니다. 따라서 이 문서는 “있는 그대로" 제공되며 더 이상 업데이트되지 않습니다.

Summary

The Microsoft C and QuickC run-time library function qsort() is useful for sorting data; however, it is necessary to provide qsort() a compare function for the type of data being sorted. This sometimes causes confusion when that type is a structure. The sample program below illustrates how to use qsort() to sort an array of structures.

More Information

In the sample code, the animal structure contains both an integer, which is the key to be sorted on, and an array of char that contains the animal's name. The compare() function receives two pointers to type struct animal and returns -1, 1, or 0 (zero) if the first element is less than, greater than, or equal to the first element, respectively.

Sample Code

/* Compile options needed: none
*
* This example program uses the C run-time library function qsort()
* to sort an array of structures.
*/

#include <stdio.h>
#include <stdlib.h>

typedef int (*compfn)(const void*, const void*);

struct animal { int number;
char name[15];
};

struct animal array[10] = { { 1, "Anaconda" },
{ 5, "Elephant" },
{ 8, "Hummingbird" },
{ 4, "Dalmatian" },
{ 3, "Canary" },
{ 9, "Llama" },
{ 2, "Buffalo" },
{ 6, "Flatfish" },
{ 10, "Zebra" },
{ 7, "Giraffe" } };

void printarray(void);
int compare(struct animal *, struct animal *);

void main(void)
{
printf("List before sorting:\n");
printarray();

qsort((void *) &array, // Beginning address of array
10, // Number of elements in array
sizeof(struct animal), // Size of each element
(compfn)compare ); // Pointer to compare function

printf("\nList after sorting:\n");
printarray();
}

int compare(struct animal *elem1, struct animal *elem2)
{
if ( elem1->number < elem2->number)
return -1;

else if (elem1->number > elem2->number)
return 1;

else
return 0;
}

void printarray(void)
{
int i;

for (i = 0; i < 10; i++)
printf("%d: Number %d is a %s\n",
i+1, array[i].number, array[i].name);
}
속성

문서 ID: 73853 - 마지막 검토: 2014. 6. 17. - 수정: 1

피드백