先上代码
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
const int maxn = 100000000;
typedef struct NODE{
struct NODE* next;
char* str;
}Node;
Node BUFF[100000000];
unsigned int ELFHash(char* str){
unsigned int hash=0;
unsigned int x=0;
while(*str){
// printf("%d\n", *str);
hash=(hash<<4)+(*str++);
if((x=hash&0xF0000000L)!=0){
hash^=(x>>24);
hash&=~x;
}
}
return (hash&0x7FFFFFFF);
}
int main(){
// for(int i = 0; i < maxn; i++){
// BUFF[i].next = NULL;
// BUFF[i].str = NULL;
// }
FILE *fp;
Node* node;
fp=fopen("dict.txt","r");
char buf[100]= {'\0'};
while(fgets(buf, 100, fp)!=NULL){
int i;
for(i = 0; i < 100; i++){
// printf("%c", buf[i]);
if(buf[i] == '\n'){
buf[i] = '\0';
break;
}
}
// printf("%s %d\n", buf, ELFHash(buf));
int pos = ELFHash(buf)%maxn;
if(BUFF[pos].str == NULL){
BUFF[pos].str = (char*)malloc(i+1);
strcpy(BUFF[pos].str, buf);
}
else{
node = &BUFF[pos];
while(node->next){
node = node->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->str = (char*)malloc(i+1);
strcpy(newNode->str, buf);
newNode->next = NULL;
node->next = newNode;
}
// printf("%s", BUFF[ELFHash(buf)%maxn].str);
// char buf[100]= {'\0'};
// getchar();
}
// printf("建表完成");
// getchar();
int res = 0;
fp = fopen("string.txt", "r");
// buf[100] = {'\0'};
//memset(buf, '\0', 100);
while(fgets(buf, 100, fp) != NULL){
for(int i = 0; i < 100; i++){
if(buf[i] == '\n'){
buf[i] = '\0';
break;
}
}
int pos1 = ELFHash(buf)%maxn;
// printf("我们在找%s", buf);
// printf("%s", BUFF[pos1]);
if(BUFF[pos1].str != NULL){
// printf("找到目的地\n");
node = &BUFF[pos1];
while(node){
// printf("要比较的字符串是%s\n", node->str);
if(strcmp(node->str, buf) == 0){
// printf("我们找到%s和%s\n", buf, node->str);
res++;
break;
}
node = node->next;
}
}
// buf[100] = {'\0'};
//memset(buf, '\0', 100);
}
printf("%d", res);
// while (fgets(buf,99,fp)!=NULL){
// printf("%s", buf);
// }
return 0;
}
说一下开发中遇到的问题,结构体的定义问题,文件一行一行读的写法,还有编译器要使用-std=c11的参数方能允许在for循环中定义整数i。最后重要的点在于要在内存中存储的值都要malloc,不能只复制一个指针(地址)到Node的str上去,要让str指向在堆中创建的字符串数组,这样在内存中会存有实体值,后面的比较值能按预期的完成操作(感谢胡同学给我指出和指导这点,否则我将永远陷入指针的漩涡中)。