嘿,我正在尝试读取文件,将其存储在哈希中,然后复制它。但是我得到了不兼容的指针类型
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};
时,代码有效
但它不适用于我的代码。请帮忙。
最佳答案
lines
被声明为 char
指针数组,但不会为它们指向的字符串分配任何空间。在您的工作版本中,编译器负责为每个字符串分配空间。
另外,您不能使用 strcpy
将 80 个指针的数组复制到 1024 个指针的数组。
相反,您读入的每一行都需要为其分配空间以供读入;那么每个地址都可以分配给 names
元素。事实上,正如 @BLUEPIXY 所建议的,line
应该是一个包含 80 个 char
的数组,而不是一个包含 80 个指向 char
的指针的数组。或者您可以为每个新行malloc
空间,并将该行的地址放入names
中。
关于c - 不兼容的指针类型的赋值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445363/