gpt4 book ai didi

c - hsearch 在哪里存储数据?

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:50 25 4
gpt4 key购买 nike

我正在使用 hsearch 研究 C 语言中的哈希表。最简单形式的问题是数据在内存中的什么位置?我认为 hcreate 创建的哈希表只是指向现有的内存位置,所以数据是通过 hcreate/hsearch 之外的方式分配的(当然 hcreate 分配的哈希表本身除外)。

为了对此进行测试,我编写了一个创建哈希表的简单程序。原始数据是一个名为“回复”的字符数组。我使用 strtok_r 将数组分成键/值对,然后使用 hsearch 创建哈希表。我使用 hsearch 执行“查找”,找到我的键值对,然后破坏原始内存,然后再次进行查找。我仍然找到它。那么数据存储在哪里呢?我没有分配任何特别的东西。下面是一些测试代码,您可以运行它来了解我的意思。您应该能够使用 gcc 编译并运行它。

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <search.h>
#include <errno.h>
#include <string.h>

/** ---------------------------------------------------------------------------
* store
*/
void store(char *key, char *value) {
ENTRY e, *ep;
e.key = key;
e.data = value;
ep = hsearch(e, ENTER);
if (ep == NULL) {
perror("hsearch");
exit(1);
}
ep->data = (char *)value;
}

/** ---------------------------------------------------------------------------
* fetch
*/
int fetch(char *key, char **value) {
ENTRY e, *ep;
e.key=key;
ep = hsearch(e, FIND);
if (ep) {
*value = (char *)ep->data;
return 1;
}
else
return 0;
}

/** ---------------------------------------------------------------------------
* main
*/
void main( void ) {
int i;
char *saveptr, *token, *subtoken, *key, *value;

// this is to simulate what a reply string looks like from my hardware...
char reply[] = "BACKPLANE_TYPE=1 BACKPLANE_REV=3 BACKPLANE_VERSION=1.0.641 BACKPLANE_ID=002428867071B05C POWER_ID=000000AC19B4 MOD_PRESENT=3F2";

hcreate(64);

if ( (token = strtok_r(reply, " ", &saveptr)) != NULL ) {
subtoken = strstr(token, "=");
subtoken++;
key = strsep(&token, "=");
store(key, subtoken);
}

do {
if ((token = strtok_r(NULL, " ", &saveptr)) != NULL) {
if ( (subtoken = strstr(token, "=")) == NULL ) break;
subtoken++;
if ( (key=strsep(&token, "=")) == NULL) break;
}
else
break;
store(key, subtoken);
} while (1);

// recall one of the key-value pairs
if (fetch((char*)"BACKPLANE_VERSION", &value)) printf("VER = %s\n", value);

// wipe everything out
saveptr= subtoken= token= key= value=NULL;
for (i=0; i<strlen(reply); i++) reply[i]='\0';

// where is the storage?
if (fetch((char*)"BACKPLANE_VERSION", &value)) printf("VER = %s\n", value);
}

最佳答案

每个数据指向reply[]数组的不同位置。您可以在第二次 fetch 之前添加 memset(reply, 0, sizeof(reply)); 并运行。第二次 fetch 什么也得不到。

关于c - hsearch 在哪里存储数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com