取消引用(模板类型)双指针char会导致segfault

时间:2017-02-20 23:59:59

标签: c++ segmentation-fault

我无法取消引用char**。特别是在这种情况下:*(array[ currentPos ].element)

arrayvector<HashEntry>类型。我的哈希表包含此类型的条目。 HashEntry类型包含以下成员。

char** element这实际上是一个模板类型,但我选择的模板是char**所以我可以存储指向我initTable函数中传递的字符串的指针,而不是复制和浪费空间我的哈希表。

EntryType info这只是一个枚举类型。

在我的课堂上,我将指向字符串的指针的地址设置为element。所以element包含我插入的指针的地址。我需要取消引用element来获取我的char *字符串,但这会导致段错误。

奇怪的是,在gdb中打印element时,它会给出指向目标字符串的指针的确切地址,但我无法取消引用它。

QuadraticHashTable<char**> table(NULL, 101); //Global Hash Table

//Main
int main()
{


    char ** docWords;

    char *s; //ifstream string buffer

    //read from ifstream and store everything that is read inside @s as a buffer
    //code that does the reading.
    //code that does the reading.
    //code that does the reading.

    docWords[0] = strtok(s, "\n");

    //Read document
    for (int i = 1; i < docSize; i++)
       docWords[i] = strtok(NULL, "\n\r");


   initTable(docWords, docSize);


   char ** wordsToFind;
   //Initialize wordsToFind to look up in hash table
   wordsToFind[0] = new char*[100];
   wordsToFind[0] = "some word";
   //repeat with the rest of the words that needs to be found

   findInTable(wordsToFind, size_of_wordsToFind);
}

//Function that init table
void initTable(char * words[], int size)
{
    //Insert words
    for (int i = 0; i < size; i++)
    {
        table.insert(&words[i]);
    }

}

void findInTable(char * words[], int size)
{
    if (table.find(&word[0]) == NULL)
    {
        //the word has not been found
    }
}



//QuadraticHashTable.h

//Class Definition
    template <class HashedObj>
    class QuadraticHashTable
    {
      public:
        explicit QuadraticHashTable( const HashedObj & notFound, int size = 101 );
        QuadraticHashTable( const QuadraticHashTable & rhs )
          : array( rhs.array), ITEM_NOT_FOUND( rhs.ITEM_NOT_FOUND ),
            currentSize( rhs.currentSize ) { }

    //stuff
    void insert( const HashedObj & x );
    enum EntryType { ACTIVE, EMPTY, DELETED };
      private:
    struct HashEntry
    {
        HashedObj element; //created with char** type
        EntryType info;
    };
    int findPos( const HashedObj & x ) const;
    vector<HashEntry> array;

    };


//QuadraticHashTable.cpp
    template <class HashedObj>
    int QuadraticHashTable<HashedObj>::findPos( const HashedObj & x ) const
    {

//Stuff

        cout << "array[ currentPos ].element: " << *(array[ currentPos ].element) << "\n"; //SEGFAULT OCCURS HERE

//Stuff
    }

    template <class HashedObj>
    void QuadraticHashTable<HashedObj>::insert( const HashedObj & x )
    {
    // Insert x as active
    int currentPos = findPos( x );

    array[ currentPos ] = HashEntry( x, ACTIVE );

        //Stuff

    }

0 个答案:

没有答案