我有调用userInteractive(* anangramInfo)的函数,该函数传入struct anangramInfo的指针,并且此结构包含指向实际字谜的指针“ anagramPointer”。
所以,我从用户那里得到了标准输入。然后将其用作bsearch的关键字,以找到指针thoese anagram具有相同的anangram.sorted。然后将指针向左移动,直到键与anagram.sorted不匹配,然后将指针向右移至anagram.word,直到anagram.sorted不匹配。但这引起了我的细分问题

#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define SIZE 80

//struct
struct anagram {
    char word[SIZE];
    char sorted[SIZE];
};

struct anagramInfo {
    struct anagram *anagramPtr;
    int             numOfAnagrams;
};



/* qsort struct comparision function (product C-string field) */
int sortedMemberCompare( const void *ptr1, const void *ptr2 )
{
    struct anagram *ia = (struct anagram *)ptr1;
    struct anagram *ib = (struct anagram *)ptr2;

    return strcmp(ia->sorted, ib->sorted);
    /* strcmp functions works exactly as expected from
    comparison function */
}

void userInteractive( struct anagramInfo *anagramInfoPtr ){

    struct anagram a;
    char data[SIZE];
    char *pos;

    printf("Enter a word to search for anagrams [^D to exit]:\n");
    fgets(data, SIZE, stdin);

    //get ripe of the '\n'
    pos=strchr(data, '\n');
    *pos = '\0';

    strncpy(a.word,data,sizeof(data));

    //lowercase word
    int i;
    for(i=0;data[i] != '\0';i++)
      {
        data[i]=(char)tolower(data[i]);
      }

    /* sort array using qsort functions */
    qsort(data,strlen(data), 1, charCompare);

    strncpy(a.sorted,data,sizeof(data));

    //struct pointer to the elements
    struct anagram *ptr= (struct anagram *)bsearch(a.sorted,anagramInfoPtr-> anagramPtr ->sorted,anagramInfoPtr-> numOfAnagrams,sizeof(struct anagram),sortedMemberCompare);

    printf(ptr->word);

    while(strncmp(ptr ->sorted,a.sorted,sizeof(a.sorted))==0) {
        ptr--;
    }

    while(strncmp(ptr ->sorted,a.sorted,sizeof(a.sorted))==0) {
        printf(ptr ->word);
        printf(" ");
        ptr++;
    }

}

最佳答案

您的疏忽是bsearch不在连续数组上搜索;它甚至没有在正确的位置搜索,因为您正在搜索排序的字符串,但是您应该搜索字谜的排序成员:

struct anagram *ptr = (struct anagram *)bsearch(&a,
            anagramInfoPtr-> anagramPtr,
            anagramInfoPtr-> numOfAnagrams,
            sizeof(struct anagram),
            sortedMemberCompare);


然后,当bsearch失败并返回NULL时,您无需检查ptr是否为NULL并使用它;因此,segfault。 (您也不要在Ctrl-D处选中NULL)。

测试

这是一个修改后的版本-我添加了charCompare函数,并用五个固定的字符串鞭打了main(),以便使其在工作后可以正常工作。

#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define SIZE 80

//struct
struct anagram {
    char word[SIZE];
    char sorted[SIZE];
};

struct anagramInfo {
    struct anagram *anagramPtr;
    int             numOfAnagrams;
};

/* qsort struct comparision function (product C-string field) */
int sortedMemberCompare( const void *ptr1, const void *ptr2 )
{
    struct anagram *ia = (struct anagram *)ptr1;
    struct anagram *ib = (struct anagram *)ptr2;

    return strcmp(ia->sorted, ib->sorted);
    /* strcmp functions works exactly as expected from
    comparison function */
}

int charCompare(const void *a, const void *b)
{
        const char *aa = a, *bb = b;
        if (*aa < *bb)
                return -1;
        if (*aa == *bb)
                return 0;
        return 1;
}

void userInteractive( struct anagramInfo *anagramInfoPtr ){

    struct anagram a;
    char data[SIZE];
    char *pos;

    printf("Enter a word to search for anagrams [^D to exit]:\n");
    fgets(data, SIZE, stdin);

    //get ripe of the '\n'
    pos=strchr(data, '\n'); // In Windows this might be a "\r" maybe?
    if (NULL == pos)
       exit(0);

    *pos = '\0';

    strncpy(a.word,data,sizeof(data));

    //lowercase word
    int i;
    for(i=0;data[i] != '\0';i++)
    {
        data[i]=(char)tolower(data[i]);
    }

    /* sort array using qsort functions */
    qsort(data, strlen(data), 1, charCompare);
    strncpy(a.sorted,data,sizeof(data));

    //struct pointer to the elements
    struct anagram *ptr = (struct anagram *)bsearch(&a,
                anagramInfoPtr-> anagramPtr,
                anagramInfoPtr-> numOfAnagrams,
                sizeof(struct anagram),
                sortedMemberCompare);

    // You must check that ptr is not NULL.
    if (NULL == ptr)
    {
        printf("Not found\n");
        return;
    }

    printf("Found: %s\n", ptr->word);

    /* Here there is a subtle error. If you find the FIRST item of the list,
       this code will position itself BEFORE THE BEGINNING of the list, and
       run a strncmp() against who knows what. Other segfault lurking! */

    while(ptr > anagramInfoPtr -> anagramPtr && strncmp(ptr ->sorted,a.sorted,strlen(a.sorted))==0) {
        ptr--;
    }

    // while(strncmp(ptr ->sorted,a.sorted,sizeof(a.sorted))==0) {
    //    ptr--;
    //}

    // Here too you should check you do not pass max number of anagrams,
    // if you hit the last item of the lot.
    while(strncmp(ptr ->sorted,a.sorted,sizeof(a.sorted))==0) {
        printf(ptr ->word);
        printf(" ");
        ptr++;
    }

}

int main()
{
        int i;
        struct anagramInfo *root;

        root = malloc(sizeof(struct anagramInfo));

        root->numOfAnagrams     = 5;
        root->anagramPtr        = malloc(root->numOfAnagrams * sizeof(struct anagram));

        strcpy(root->anagramPtr[0].word, "oriental");
        strcpy(root->anagramPtr[1].word, "teaching");
        strcpy(root->anagramPtr[2].word, "senator");
        strcpy(root->anagramPtr[3].word, "admirer");
        strcpy(root->anagramPtr[4].word, "rescued");

        for (i = 0; i < root->numOfAnagrams; i++)
        {
            int j;
            for (j = 0; root->anagramPtr[i].word[j]; j++)
               root->anagramPtr[i].word[j] = tolower(root->anagramPtr[i].word[j]);
            strcpy(root->anagramPtr[i].sorted, root->anagramPtr[i].word);
            qsort(root->anagramPtr[i].sorted, strlen(root->anagramPtr[i].sorted), 1, charCompare);
        }
        qsort(root-> anagramPtr, root-> numOfAnagrams, sizeof(struct anagram), sortedMemberCompare);
        for (;;)
            userInteractive(root);
    }




$ gcc -W -Wall -o anagram anagram.c
$ ./anagram
Enter a word to search for anagrams [^D to exit]:
treason
Found: senator

Enter a word to search for anagrams [^D to exit]:
cheating
Found: teaching

Enter a word to search for anagrams [^D to exit]:
relation
Found: oriental

Enter a word to search for anagrams [^D to exit]:

$

关于c - C bsearch导致段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13502202/

10-14 15:43