【发布时间】:2017-01-07 10:25:26
【问题描述】:
我正在为一个类开发一个拼写检查程序,但在尝试使用指针使其他函数可以访问散列数组时遇到了麻烦。
以下只是一小部分代码,因为程序太大而无法粘贴。这部分代码的基本思路是:
-创建数组和指向数组的指针。 -散列每个单词并将该值用作数组中的索引。 - 使用指针存储散列值。 - 使用数组指针和散列值访问数组。
如下所述,直接访问存储在数组中的单词是可行的,但是在尝试使用指针访问存储在数组中的单词时出现段错误。
==1845== Invalid read of size 8
==1845== at 0x401367: load (dictionary.c:133)
==1845== by 0x40095D: main (speller.c:45)
==1845== Address 0xfffc3fab8 is not stack'd, malloc'd or (recently) free'd
char** hash_array = calloc(HASH_TABLE_SIZE, sizeof(*hash_array));
char*** array_pointer;
// storing the address of the hash array in pointer
array_pointer = &hash_array;
uint32_t* hash_pointer;
hash_pointer = NULL;
uint32_t hash = hashlittle(word_buffer, word_length, 1578459744);
hash_pointer = &hash;
// this prints out the word successfully
printf("word in h-array: %s\n", hash_array[hash]);
// this seg faults
printf("word in h-array: %s\n", *array_pointer[*hash_pointer]);
【问题讨论】:
-
试试
(*array_pointer)[*hash_pointer] -
老实说,在这段代码中,
array_pointer毫无意义。存储自动变量的地址似乎毫无意义,特别是因为它稍后的使用正是让你绊倒的事情。与hash_pointer类似。为什么不直接使用hash_array[hash]。 ?? -
@Carlos: 在
int* x, y;中y的类型是什么? -
@WhozCraig。我希望能够在创建它的函数之外访问数组。指针在那里,因为我不想在将数组传递给另一个函数时创建数组的副本。
-
@iharob。不确定您的问题的相关性是什么。我的代码中没有类似的东西。