链接列表数组C ++

时间:2014-01-29 02:12:21

标签: c++ arrays pointers data-structures linked-list

所以我认为我理解了如何实现一个指针数组,但我的编译器说不然=(。任何帮助都会受到赞赏,我觉得我很接近,但我错过了一些至关重要的东西。

1。)我有一个名为node的结构声明:。

struct node {

int num;

node *next;

}

2。)我已经声明了一个指针数组的指针,如下所示:

node **arrayOfPointers;

3。)然后我通过这样做动态地创建了指针数组:

arrayOfPointers = new node*[arraySize];

此时我的理解是,arrayOfPointers现在指向x节点类型的数组,其中x = = arraySize。

4.但是当我想访问arrayOfPointers中的第五个元素以检查它的下一个指针是否为空时,我收到了一个分段错误错误。使用这个:

if (arrayOfPointers[5]->next == NULL)

{

cout << "I'm null" << endl;

}

有谁知道为什么会这样?我可以通过执行以下操作为num赋值:arrayOfPointers [5] - &gt; num = 77;

但是我很困惑为什么检查结构中的指针导致错误。此外,虽然我们正在使用它,将arrayOfPointers传递给函数的正确原型是什么?它仍然是(节点** arrayOfPointers)还是其他类似的东西(node *&amp; arrayOfPointers)?

提前感谢您提供的任何提示或指示(哈哈)!

完整代码(已更新):

 /*
* Functions related to separate chain hashing
*/

struct chainNode
{
    int value;
    chainNode *next;
};

chainNode* CreateNewChainNode (int keyValue)
{
    chainNode *newNode;

    newNode = new (nothrow) chainNode;

    newNode->value = keyValue;
    newNode->next = NULL;

    return newNode;
}


void InitDynamicArrayList (int tableSize, chainNode **chainListArray)
{

    // create dynamic array of pointers
    chainListArray = new (nothrow) chainNode*[tableSize];

    // allocate each pointer in array
    for (int i=0; i < tableSize; i++)
    {
        chainListArray[i]= CreateNewChainNode(0);
    }

    return;
}


bool SeparateChainInsert (int keyValue, int hashAddress, chainNode **chainListArray)
{
    bool isInserted = false;
    chainNode *newNode;

    newNode = CreateNewChainNode(keyValue);    // create new node

    // if memory allocation did not fail, insert new node into hash table
    if (newNode != NULL)
    {
        //if array cell at hash address is empty
        if (chainListArray[hashAddress]->next == NULL)
        {
            // insert new node to front of list, keeping next pointer still set to NULL
            chainListArray[hashAddress]->next = newNode;

        }
        else //else cell is pointing to a list of nodes already
        {
            // new node's next pointer will point to former front of linked list
            newNode->next = chainListArray[hashAddress]->next;

            // insert new node to front of list
            chainListArray[hashAddress]->next = newNode;

        }

        isInserted = true;
        cout << keyValue << " inserted into chainListArray at index " << hashAddress << endl;
    }

    return isInserted;
}

/*
* Functions to fill array with random numbers for hashing
*/

void FillNumArray (int randomArray[])
{
    int i = 0;                                  // counter for for loop
    int randomNum = 0;                          // randomly generated number

    for (i = 0; i < ARRAY_SIZE; i++)            // do this for entire array
    {
        randomNum = GenerateRandomNum();             // get a random number

        while(!IsUniqueNum(randomNum, randomArray))  // loops until random number is unique
        {
               randomNum = GenerateRandomNum();
        }

        randomArray[i] = randomNum;                  // insert random number into array
    }

    return;
}


int GenerateRandomNum ()
{
    int num = 0;                               // randomly generated number

    // generate random number between start and end ranges
    num = (rand() % END_RANGE) + START_RANGE;

    return num;
}

bool IsUniqueNum (int num, int randomArray[])
{
    bool isUnique = true;         // indicates if number is unique and NOT in array
    int index = 0;                // array index

        //loop until end of array or a zero is found
        //(since array elements were initialized to zero)
        while ((index < ARRAY_SIZE) && (!randomArray[index] == 0))
        {
            // if a value in the array matches the num passed in, num is not unique
            if (randomArray[index] == num)
            {
                isUnique = false;
            }

            index++;            // increment index counter

        }   // end while

    return isUnique;
}



/*
*main
*/

int main (int argc, char* argv[])
{
    int randomNums[ARRAY_SIZE] = {0};     // initialize array elements to 0
    int hashTableSize = 0;                // size of hash table to use
    chainNode **chainListArray;
    bool chainEntry = true;     //testing chain hashing

    //initialize random seed
    srand((unsigned)time(NULL));

    FillNumArray(randomNums);           // fill randomNums array with random numbers

    //test print array
    for(int i = 0; i < ARRAY_SIZE; i++)
    {
        cout << randomNums[i] << endl;
    }

    //test chain hashing insert
    hashTableSize = 19;
    int hashAddress = 0;

    InitDynamicArrayList(hashTableSize, chainListArray);

    //try to hash into hash table
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        hashAddress = randomNums[i] % hashTableSize;
        chainEntry = SeparateChainInsert(randomNums[i], hashAddress, chainListArray);
    }


    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:9)

arrayOfPointers = new node*[arraySize];

返回一堆未分配的指针。你的顶级数组很好,但它的元素仍然是未初始化的指针,所以当你这样做时:

->next

您调用未定义的行为。您正在取消引用未初始化的指针。

您正确分配了数组,现在需要分配每个指针,即

for(int i = 0; i < arraySize; ++i) {
    arrayOfPointers[i] = new node;
}

顺便说一句,我意识到你正在学习,但你应该意识到你实际上是在这里写C。在C ++中,您拥有无数精彩的数据结构,可以为您处理内存分配(更重要的是,重新分配)。

答案 1 :(得分:0)

您的代码很好,但它是关于您如何声明您的InitDynamicArrayList。一种方法是使用*** chainListArray,或更像C ++的语法来使用这样的引用:

void InitDynamicArrayList(int tableSize,chainNode **&amp; chainListArray)