[英]When I pass an array (a hash table) to update it to another function , I do not get the updated table back in main
typedef struct hashtable
{
char str[15];
struct hashtable *next;
}htable;
int hashkey(char *str)
{
//correctly returns hash key
}
int hash(htable * ht, char str[15], int key)
{
//error checking done
if(ht[key].next==NULL)
{
htable * temp = (htable *)malloc(sizeof(ht));
strncpy(temp->str, str,15);
temp->next = NULL;
//printf("%s %d\n",temp->str,key);
ht[key].next = temp;
//printf("%s %d\n",ht[key].next->str,key);
return 1;
}
}
void main()
{
int cnt=0,key;
FILE *fp = fopen("Keywords.txt","r");
if(fp==NULL)
{
printf("Error\n");
return;
}
while(fgetc(fp)!=EOF)
cnt++;
htable ht[cnt];
char aa[15];
rewind(fp);
while(fgets(aa,15,fp))
{
key=hashkey(aa);
if(hash(ht,aa,key))
{
printf("%s %d\n",ht[key].str,key);
}
}
}
The output when the keywords are : and, as, assign, attribute 关键字为: 和(as,assign)属性时的输出
is 是
14 7 47 100
14 7 47 100
But i expect the output to be and, as, assign, attribute 但我希望输出是和属性分配
What I don't understand is that when I send ht array to hash(), shouldn't the pointer in hash() modify the memory location? 我不明白的是,当我将ht数组发送到hash()时,hash()中的指针是否不应该修改内存位置? So when I try to access the same memory location, shouldn't I be getting the stored values and not these random numeric values.
因此,当我尝试访问相同的内存位置时,是否应该获取存储的值而不是这些随机数值。 Thanks!
谢谢! :)
:)
Look at the memory allocation: 看一下内存分配:
int hash(htable * ht, char str[15], int key) {
//...
htable * temp = (htable *)malloc(sizeof(ht));
ht
is a pointer and you here are allocating memory for the pointer (4 or 8 bytes), not for the structure htable
. ht
是一个指针,您在这里为该指针(4或8个字节)分配内存,而不是为htable
结构分配内存。 Correct is: 正确的是:
htable * temp = (htable *)malloc(sizeof(htable));
And also: you are initializing ht[key].next
, while then printing ht[key]
: 而且:您正在初始化
ht[key].next
,然后打印ht[key]
:
//printf("%s %d\n",ht[key].next->str,key); // this prints OK
printf("%s %d\n",ht[key].str,key); // this probably is not initialized
Got the answer. 得到了答案。 Thanks Alexey but that wasn't really the problem.
感谢Alexey,但这并不是真正的问题。 In the main function while printing i was trying to print the string stored in the hash table's index.
在打印时的主要功能中,我试图打印存储在哈希表索引中的字符串。
printf("%s %d\n",ht[key].str,key);
Instead I should be printing string at the location that the index points to (and not the index). 相反,我应该在索引指向的位置(而不是索引)打印字符串。
printf("%s %d\n",ht[key].next->str,key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.