- 论坛徽章:
- 0
|
这是我写的查字典程序。但是编译的时候卡在invalid use of flexible array member这个问题上- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #define MAX_SIZE 128
- #define BUFFER_SIZE 4096
- #define WORD_LEN 100
- typedef struct {
- char* key_word;
- int n_trans;
- char* trans[];
- }word_t;
- word_t *dict = NULL;
-
- int search(word_t* dict, int start, int end, char* buf){
- int mid = (start+end)/2;
- if(start > end)
- return -1;
- if(strcmp(dict[mid].key_word, buf) == 0)
- return mid;
- else if(strcmp(dict[mid].key_word, buf) == -1)
- return search(dict, mid+1, end, buf);
- else
- return search(dict, start, mid-1, buf);
- }
- int main(int argc, char* argv[]){
- int num = 0;
- int len,n,i,j,len_trans;
- char str[100];
- char buf[MAX_SIZE];
- char* p=NULL;
- int id;
- FILE* dict_fp=NULL, *bin=NULL;
-
-
- if((dict_fp = fopen("dict.txt","r")) == NULL){
- perror("fopen dict");
- return -1;
- }
- if((bin = fopen("dict.dat","wb+")) == NULL){
- perror("fopen dict.dat");
- return -1;
- }
- while(fgets(buf, MAX_SIZE, dict_fp) != NULL){
- if(buf[0] == '#'){
- num++;
- }
- }
-
- printf("there are %d words\n", num);
- fwrite(&num, sizeof(int), 1, bin);
- rewind(dict_fp);
- while(fgets(buf, MAX_SIZE, dict_fp)!=NULL){
- if(buf[0] == '#'){
-
- len = strlen(buf)-2;
- fwrite(&len, sizeof(int), 1, bin);
- fwrite(&buf[1], len, 1, bin);
- }else{
-
- n = 0;
- buf[len-1]='@';
- for(i=0; buf[i]!='\0'; i++){
- if(buf[i]=='@')
- n++;
- }
- fwrite(&n, sizeof(int), 1, bin);
- p = &buf[6];
-
- for(i=0; buf[i]!='\0'; i++){
- if(buf[i]=='@')
- buf[i] = '\0';
- }
-
- for(i=0; i<n; i++){
- len_trans = strlen(p);
- fwrite(&len_trans, sizeof(int), 1, bin);
- fwrite(p, len_trans, 1, bin);
- p = p+strlen(p)+1;
-
- }
- }
- }
- close(dict_fp);
- printf("init dict.dat is done....\n");
- rewind(bin);
- fread(&num, sizeof(int), 1, bin);
- dict = (word_t*)malloc(sizeof(word_t) * num);
- for(i=0; i<num; i++){
- fread(&len, sizeof(int), 1, bin);
- dict[i].key_word = (char*)malloc(sizeof(char)*(len + 1));
- fread(dict[i].key_word, len, 1, bin);
- dict[i].key_word[len] = '\0';
- fread(&dict[i].n_trans, sizeof(int), 1, bin);
- [color=Red]dict[i].trans = (char**)malloc(sizeof(char*) * dict[i].n_trans);//出现问题的地方[/color]
- for(j=0; j<dict[i].n_trans; j++){
- fread(&len_trans, sizeof(int), 1, bin);
- dict[i].trans[j] = (char*)malloc(sizeof(char) * (len_trans+1));
-
- fread(dict[i].trans[j], len_trans, 1, bin);
- dict[i].trans[j][len_trans]='\0';
- }
-
- }
- printf("init dict....\n\n");
- while(1){
- printf("please input the word you want to find out, input '_quit' to quit\n");
- fgets(str, WORD_LEN, stdin);
-
- str[strlen(str)-1] = '\0';
- if(strcmp(str,"_quit") == 0)
-
- return 0;
- else
- id = search(dict, 0, num-1, str);
- if(id == -1)
-
- printf("fail to find out\n");
- else
- {
- printf("%s\n",dict[id].key_word);
- printf("Trans:");
- for(i=1; i<=dict[id].n_trans; i++){
-
- printf(" %d %s",i , dict[id].trans[i]);
- }
- putchar('\n');
- }
- }
- // close(bin);
- return 0;
-
- }
复制代码 |
|