Strcpy 在用户定义的数组中不起作用

Strcpy doesn't work in user defined array

我正在尝试为输入文本文件分配元素哈希 table[TABLE_SIZE]。所以我使用了 strcpy 函数。但是它没有复制到数组中。

我试过 malloc 来制作数组以便写入其中。但它没有用,所以我做了一个元素*类型变量指向 hash_table array.But 仍然没有用。

    //this is the header file

        typedef struct {
            char key[100];
            char data[100];
        } element;

        element hash_table[TABLE_SIZE];    


        // For caomparison count
        int num_comparison;

        // 파일에서 단어들을 읽어 해시테이블 구성
        int build_dictionary(char *fname);

        int build_dictionary(char *fname) {
            int  i = 0; // num of data
            char key[100], data[200]; 
            FILE *ifp;

                //pointing to the hash_table array
            element* hash_table_p = hash_table;
            hash_table_p = (element*)malloc(sizeof(element));


                //file opening error
            if ((ifp = fopen(fname, "r")) == NULL) {
                printf("No such file ! \n");
                exit(1);
            }
            while (fscanf(ifp, "%s %s", key, data) == 2) { 
                // (key data) assigning to array

                    //i've tried this because hash_table[i].data didn't work
                strcpy(hash_table_p->data, data);
                strcpy(hash_table_p->key, key);

                    strcpy(hash_table[i].data, hash_table_p->data);
                    strcpy(hash_table[i].key, hash_table_p->key);
                i++;

                 //checking if it is well done
                printf("  %s %s \n", hash_table_p->key, hash_table_p->data);
                printf(" %d %s %s \n",i , hash_table[i].data, hash_table[i].key );
             }
                fclose(ifp);
            return(i);

        }
//the input text file went as below
one 하나
two 둘
three 셋
four 넷
five 다섯

当我执行build_dictionary函数时,只有一个hash_table_p strcpy被分配好而hash_table里面什么都没有。

        element* hash_table_p = hash_table;
        hash_table_p = (element*)malloc(sizeof(element));

你正在覆盖第一个分配(当你调用 malloc 时为 hash_table_p 获得新空间),据我所知你已经定义了 table 的大小,所以你不需要保留更多 space (删除带有 malloc 的行)并且只需在每次迭代中增加指针的位置(就像你已经在做的那样)。