-3

嘿,所以我试图尝试读取文件,将其存储在哈希中,然后复制它。但是我得到了不兼容的指针类型

struct hash_struct {
    int id;                   
    char name[BUFFER_SIZE];            /* key (string WITHIN the structure */
    UT_hash_handle hh;         /* makes this structure hashable */
};

int main(int argc, char *argv[] )
{
    char *lines[80];
    FILE* fp = fopen("file.txt","r");
    if(fgets(*lines, BUFFER_SIZE, fp) != NULL)
    {
        puts(*lines);
        // do something
    }
    fclose(fp);
    const char **n;
    char *names[1024];
    strcpy(*names, *lines);
    struct hash_struct *s, *tmp, *users = NULL;
    int i=0;
for (n = names; *n != NULL; n++) 
{
    s = (struct hash_struct*)malloc(sizeof(struct hash_struct));
    strncpy(s->name, *n,10);
    s->id = i++;
    HASH_ADD_STR( users, name, s );
}

HASH_FIND_STR( users, "joe", s);
if (s) printf("joe's id is %d\n", s->id);
printf("Hash has %d entries\n",HASH_COUNT(users));

/* free the hash table contents */
HASH_ITER(hh, users, s, tmp) {
  HASH_DEL(users, s);
  free(s);
}
return 0;

}

该代码在我初始化时有效,const char **n, *names = {array elements here}; 但它不适用于我拥有的代码。请帮忙。

4

1 回答 1

0

lines被声明为一个char指针数组,但不为它们指向的字符串分配任何空间。在您的工作版本中,编译器负责为每个字符串分配空间。

另外,您不能使用strcpy将 80 个指针的数组复制到 1024 个指针的数组。相反,您读入的每一行都需要分配空间以供读入;然后可以将其中每个的地址分配给 的元素names。事实上,正如@BLUEPIXY 建议的那样,line应该是一个 80 个char数组,而不是一个 80 个指针数组char。或者您可以只malloc为每个新行留出空间,并将该行的地址放入names.

于 2014-10-18T22:57:44.683 回答