【问题标题】:Properly dereferencing an array of strings正确取消引用字符串数组
【发布时间】: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。不确定您的问题的相关性是什么。我的代码中没有类似的东西。

标签: c arrays pointers hash


【解决方案1】:

您看到的问题是因为取消引用运算符* 的运算符优先级。

以下都是等价的:

*array_pointer[*hash_pointer]

*array_pointer[hash]

*(array_pointer[hash])

*((&hash_array)[hash])

*(*(&hash_array + hash))

问题在这里:*(&hash_array + hash)。您正在尝试取消引用指向某个内存位置偏移量的指针,该位置偏离指针 hash_array 的存储位置,而不是它指向的位置,这会导致未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多