问题:解释一下我备注错误的地方为什么会使程序崩溃。
开发IDE:codeblock17.12
链接:https://pan.baidu.com/s/1wwoP4v_Y5xYJtH7WZIWjdw 密码:gm87
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct element
{
char *key;
char *content;
}element;
char buf[2048]={0};
int get_elements(element **p,char * file_name)
{
FILE * fp=fopen(file_name,"r");
if(fp==NULL)
{
printf("打开文件失败!");
return -1;
}
*p=(element*)malloc(sizeof(element));
//char buf[2048]={0};
int index=0;
while(!feof(fp))
{
if(fgets(buf,sizeof(buf),fp)!=NULL)
{
(*p)[index].key=(char *)calloc(strlen(buf),sizeof(char));
//strcpy((*p)[index].key,buf);//错误
//strncpy((*p)[index].key,buf,strlen(buf));//错误
//strcpy((*p)[index].key,&buf[0]);//错误
strcpy((*p)[index].key,&buf[1]);//正确
memset(buf,0,sizeof(buf));
}
if(fgets(buf,sizeof(buf),fp)!=NULL)
{
(*p)[index].content=(char *)calloc(strlen(buf),sizeof(char));
//strcpy((*p)[index].content,buf);
strcpy((*p)[index].content,&buf[6]);
memset(buf,0,sizeof(buf));
}
printf("%s%s",(*p)[index].key,(*p)[index].content);
index++;
if((*p=(element*)realloc(*p,sizeof(element)*(index+1))) == NULL)
{
puts("error");
return -1;
}
//memset(*p+index,0,sizeof(element));
}
fclose(fp);
return index;
}
int search_element(element *p,int n,const char * key)
{
int i=0;
for(i=0;i<n;i++)
{
//if(strcmp(p[i].key,key)==0)//p[i].key[3]是'\n'字符,key[3]是'\0'字符
if (strncmp(p[i].key, key, strlen(key)) == 0)
{
printf("%s",p[i].content);
return 1;
}
}
return -1;
}
//最好还是传指针的地址,不然就是野指针
int free_elements(element *p,int n)
{
int i=0;
for(i=0;i<n;i++)
{
if (p[i].key)
free(p[i].key);
if (p[i].content)
free(p[i].content);
}
free(p);
return 0;
}
int main()
{
char file_name[]="dict.txt";
element *p=NULL;
int n = get_elements(&p,file_name);//将词典的内容读到内存
search_element(p,n,"you");
free_elements(p,n);
return 0;
}
工程文件包:
链接:https://pan.baidu.com/s/1FfHerOqcVlGoP3-vSvXMIA 密码:b1gu