通过POSIX hcreate/hsearch功能implented使用关联数组(如描述here,我挣扎着,我从来没有进入一些意外的行为寻找钥匙或周围的其他方法。 我跟踪它到商店按引用的一些实例-instead-的价值 这令我感到诧异,因为在该示例使用字符串文字作为关键字:如何在C中通过hcreate/hsearch(通过值而不是引用)实现关联数组的键?
store("red", 0xff0000);
store("orange", 0x123456); /* Insert wrong value! */
store("green", 0x008000);
store("blue", 0x0000ff);
store("white", 0xffffff);
store("black", 0x000000);
store("orange", 0xffa500); /* Replace with correct value. */
这里是一个MWE,显示我的问题:
#include /* intptr_t */
#include /* hcreate(), hsearch() */
#include /* perror() */
#include /* exit() */
#include /* strcpy() */
void exit_with_error(const char* error_message){
perror(error_message);
exit(EXIT_FAILURE);
}
int fetch(const char* key, intptr_t* value){
ENTRY e,*p;
e.key=(char*)key;
p=hsearch(e, FIND);
if(!p) return 0;
*value=(intptr_t)p->data;
return 1;
}
void store(const char *key, intptr_t value){
ENTRY e,*p;
e.key=(char*)key;
p = hsearch(e, ENTER);
if(!p) exit_with_error("hash full");
p->data = (void *)value;
}
void main(){
char a[4]="foo";
char b[4]="bar";
char c[4]="";
intptr_t x=NULL;
if(!hcreate(50)) exit_with_error("no hash");
store(a,1); /* a --> 1 */
strcpy(c,a); /* remember a */
strcpy(a,b); /* set a to b */
store(a,-1); /* b --> -1 */
strcpy(a,c); /* reset a */
if(fetch(a,&x)&&x==1) puts("a is here.");
if(!fetch(b,&x)) puts("b is not.");
strcpy(a,b); printf("But if we adjust a to match b");
if(fetch(a,&x)&&x==-1&&fetch(b,&x)&&x==-1) puts(", we find both.");
exit(EXIT_SUCCESS);
}
Compili Ng和上述C代码产生以下输出执行:
a is here.
b is not.
But if we adjust a to match b, we find both.
我将需要读取文件,并存储了一大批串:整数对,然后我需要阅读的第二文件,以检查偶数以前存储的值的字符串数量较多。
我不明白如果通过引用来比较键,这将如何实现。
如何更改我的关联数组实现以按值存储键?
如果这是不可能的,那么考虑到上述用例,我该如何解决这个问题?
编辑:
这个问题只涉及与输入密钥,但没有找到。 也会出现相反的问题,并在this question中详细介绍。
2016-01-12
mschilli
+0
[C hsearch找到之前未输入的值]的可能重复(http://stackoverflow.com/questions/34752934/c-hsearch-finds-values-not-entered-before) –