我正試圖在哈希表中插入一個整數。要做到這一點,我創建了一個節點*的數組,我試圖讓像listarray[i]->data=5
這樣的分配成爲可能。不過,我仍然對指針感到困惑,而且我在評論'//這裏崩潰'時就崩潰了,我不明白爲什麼。我在main()中的初始化是否無效?插入哈希表
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node * next;
} node;
//------------------------------------------------------------------------------
void insert (node **listarray, int size)
{
node *temp;
int value = 11; //just some random value for now, eventually will be scanned in
int index = value % size; // 11 modulo 8 yields 3
printf ("index is %d\n", index); //prints 3 fine
if (listarray[index] == NULL)
{
printf("listarray[%d] is NULL",index); //prints because of loop in main
listarray[index]->data = value; //crashes here
printf("listarray[%d] is now %d",index,listarray[index]->data); //never prints
listarray[index]->next = NULL;
}
else
{
temp->next = listarray[index];
listarray[index] = temp;
listarray[index]->data = value;
}
}//end insert()
//------------------------------------------------------------------------------
int main()
{
int size = 8,i; //set default to 8
node * head=NULL; //head of the list
node **listarray = malloc (sizeof (node*) * size); //declare an array of Node *
//do i need double pointers here?
for (i = 0; i < size; i++) //malloc each array position
{
listarray[i] = malloc (sizeof (node) * size);
listarray[i] = NULL; //satisfies the first condition in insert();
}
insert(*&listarray,size);
}
輸出:
index is 3
listarray[3] is NULL
(崩潰)
所需的輸出:
index is 3
listarray[3] is NULL
listarray[3] is now 11
請問爲什麼這是downvoted?這是我困惑的一個問題,我給了我寫的東西的推理,而不是把它全部粘貼在一起,沒有任何解釋。 – user3507072 2014-10-18 18:14:34
我沒有downvote,但也許downvote是因爲你在你的代碼中做了一些髮型的東西。例如:你做'listarray [i] = malloc ...',然後在下一行你做'listarray [i] = NULL'。這根本沒有任何意義...... – honk 2014-10-18 18:25:57
另一個好的方法是:你檢查'listarray [index] == NULL'是否可以,然後你訪問'listarray [index] - > data' ... – honk 2014-10-18 18:29:46