⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 strsort.c

📁 c21Examples.rar
💻 C
字号:
/* Using qsort() and bsearch() with strings. */

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

#define MAX 20

int comp(const void *s1, const void *s2);

int main( void )
{
    char *data[MAX], buf[80], *ptr, *key, **key1;
    int count;

    /* Input a list of words. */

    printf("Enter %d words, pressing Enter after each.\n",MAX);

    for (count = 0; count < MAX; count++)
    {
        printf("Word %d: ", count+1);
        gets(buf);
        data[count] = malloc(strlen(buf)+1);
        strcpy(data[count], buf);
    }

    /* Sort the words (actually, sort the pointers). */

    qsort(data, MAX, sizeof(data[0]), comp);

    /* Display the sorted words. */

    for (count = 0; count < MAX; count++)
        printf("\n%d: %s", count+1, data[count]);

    /* Get a search key. */

    printf("\n\nEnter a search key: ");
    gets(buf);

    /* Perform the search. First, make key1 a pointer */
    /* to the pointer to the search key.*/

    key = buf;
    key1 = &key;
    ptr = bsearch(key1, data, MAX, sizeof(data[0]), comp);

    if (ptr != NULL)
        printf("%s found.\n", buf);
    else
        printf("%s not found.\n", buf);
    return 0;
}

int comp(const void *s1, const void *s2)
{
    return (strcmp(*(char **)s1, *(char **)s2));
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -