我正在尝试研究C,我正在使用char*和char数组来解决问题.我正在使用库中的通用哈希集容器(我不想详细描述).该库包含该功能
void *HashSetLookup(hashset *h, const void *elemAddr);
Run Code Online (Sandbox Code Playgroud)
我必须使用它来搜索哈希集以查看该元素是否已经存在(哈希和比较函数是哈希集结构的一部分).在这种情况下,我使用hashset来存储指向C字符串的指针,或者更具体地说(char**).我的问题是以下代码给出了分段错误:
char word[1024];
/* Some code that writes to the word buffer */
HashSetLookup(stopList, &word);
Run Code Online (Sandbox Code Playgroud)
虽然这段代码工作正常(并按预期):
char word[1024];
/* The same code as before that writes to the word buffer */
char* tmp = strdup(word);
HashSetLookup(stopList, &tmp);
free(tmp);
Run Code Online (Sandbox Code Playgroud)
我认为char word []和char*基本上是一样的.唯一的区别是char字[1024]在堆栈中具有固定长度1024,但堆中的tmp仅占用所需的空间(strlen(word)+1).
因此,我不明白为什么我必须在堆中复制字符串才能调用此函数.为什么会这样?char*tmp = strdup("something")和char word [1024] ="something"之间是否存在一些更基本的区别?
你提到你需要一个char **有这就是问题所在:一个数组,word并&word意味着同样的事情-数组内容的实际位置.使用指针时它起作用的原因是因为"指针" 存储在不同的位置,而它指向同一个数组.你不需要strdup,你只需要创建一个指针:
char* tmp = word;
HashSetLookup(stopList, &tmp);
Run Code Online (Sandbox Code Playgroud)