我有函数调用 userInteractive(*anangramInfo),它传入结构 anangramInfo 的指针,这个结构包含指向实际字谜的指针“anagramPointer”。所以,我从用户那里得到了标准输入。然后使用它作为 bsearch 的键来查找指针,这些字谜具有相同的 anangram.sorted。然后将指针向左移动,直到键与 anagram.sorted 不匹配,然后移回右侧 printf 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++;
}
}