[英]Pointers to pointers in hash Tables
i don't quite understand why the following code does what it does. 我不太明白为什么以下代码会这样做。
void initializeTable()
{
NodeT* (*hashTable) ;
*hashTable=(NodeT*)malloc(30*sizeof(NodeT));
int i;
for(i=0;i<30;i++)
{
(*hashTable)[i].info=(char*)malloc(10*sizeof(char));
strcpy((*hashTable)[i].info,"a");
cout<<(*hashTable)[i].info<<" ";
}
}
I am trying to understand how hash Tables work. 我试图了解哈希表如何工作。 In the first version of my program I used something like NodeT* hashTable[arraySize]
in order to create an array of pointers to NodeT
, in order to do the chaining. 在程序的第一个版本中,我使用了诸如NodeT* hashTable[arraySize]
类的东西来创建指向NodeT
的指针数组,以进行链接。 After this I decided to try and allocate dinamycally memory for the array, so I tried to use the (I think) equivalent NodeT* (*mockTable)
. 之后,我决定尝试为数组分配动态内存,因此我尝试使用(我认为)等效的NodeT* (*mockTable)
。
My question is the following: why do I have to use (*hashTable)[i].info
, and not (*hashTable)[i]->info
? 我的问题如下:为什么我必须使用(*hashTable)[i].info
而不是(*hashTable)[i]->info
? As far as i concerned, hashTable
is a pointer which points to an array of pointers to NodeT
, so this shouldn't happen. 就我而言, hashTable
是一个指向NodeT
的指针数组的指针,因此这不应该发生。 What am i getting wrong here? 我这是怎么了?
You got the basic idea but it seem you miscount the pointers your hashTable is a pointer to pointer (**), and when you access it in the strcpy you actually get into the value of this double pointer the 1'st is with the array index [i] and the second is with the *hashTable which is when accessing a variable calling the Value inside it. 您有基本的想法,但似乎您误算了指针,您的hashTable是指向指针(**)的指针,当您在strcpy中访问它时,您实际上进入了这个双指针的值,数组的第1个是索引[i],第二个与* hashTable一起使用,该表是在访问其中调用Value的变量时使用的。 so if you define a duel pointer variable StrutT **temp; 因此,如果您定义了决斗指针变量StrutT ** temp; and you want to access a field inside it you can *temp[i].field but in case you would only want to access at level of a single pointer (same **temp) you would need: temp[i]->field or *temp->field which both only "pop" the top most pointer 并且您想访问其中的字段,可以使用* temp [i] .field,但是如果您只想访问单个指针(相同的** temp)级别,则需要:temp [i]-> field或* temp-> field都只能“弹出”最上面的指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.