我已经成功创建了一个新的,更大的哈希表,它重新散列当前表中的数据并将其插入到新表中。然而,事实证明我想要做出的改变是在本地反映出来的,而不是传递给主要的。在下面的代码段的底部,我注释了**listarray=**listarray2;
行,因为我不认为这就是我想要发生的事情。我知道代码的其余部分正常工作,因为在我的insert()函数中,不同的数组位置存储相同的值。
我唯一的问题:如何让listarray2覆盖listarray,以便它作为我的默认表反映在main中?
void resizeTable (node **listarray, int *size)
{
//listarray is an array of node*, declared in main just like listarray2
//size is 8, should reflect the change to 11 back in main
int newSize= 11;
node *temp; //iterating pointer
node **listarray2= malloc (sizeof (node*) * newSize); //create space for a new array of node*'s
for(i=0;i<newSize;i++)
listarray2[i]=NULL; //set everything inside to NULL
//go through original listarray (of size 8)
for(i=0;i<(*size);i++)
{
if (listarray[i]==NULL) //ignore empty array positions
continue;
temp=listarray[i]; //temp now points to a node that is not NULL
while(temp!=NULL) //until the end of the list in that particular array
{
//arg1 is the new list,arg2 is the new Size 11, arg3 is the data from the to-be-old hash table
insert(&*listarray2,newSize,temp->data);
temp=temp->next;
}
}
//free(listarray);
//**listarray=**listarray2;
*size = newSize;
}//end resize()
答案 0 :(得分:1)
为了清楚起见,重命名一些变量,你会这样做:
#include "assert.h"
void resizeTable (node ***p_listarray, int *p_size)
{
//listarray is an array of node*, declared in main just like newListarray
//size is 8, should reflect the change to 11 back in main
node **newListarray;
int newSize= 11;
node **oldListarray;
int oldSize;
int i;
assert(p_listarray != NULL); /* From http://en.wikipedia.org/wiki/Assert.h */
assert(p_size != NULL); /* From http://en.wikipedia.org/wiki/Assert.h */
oldListarray = *p_listarray;
oldSize = *p_size;
newListarray = malloc (sizeof (node*) * newSize); //create space for a new array of node*'s
for(i=0;i<newSize;i++)
newListarray[i]=NULL; //set everything inside to NULL
//go through original listarray (of size 8)
for(i=0;i<oldSize;i++)
{
node *temp; //iterating pointer
if (oldListarray[i]==NULL) //ignore empty array positions
continue;
temp=oldListarray[i]; //temp now points to a node that is not NULL
while(temp!=NULL) //until the end of the list in that particular array
{
//arg1 is the new list,arg2 is the new Size 11, arg3 is the data from the to-be-old hash table
insert(&*newListarray,newSize,temp->data);
temp=temp->next;
}
}
*p_listarray = newListarray;
*p_size = newSize;
free(oldListarray);
}//end resize()
然后将其称为
node **listarray;
int size;
// Initialize the hash table, and then when it needs resizing...
resizeTable(&listarray, &size);