再说一遍,我有一个非常愚蠢的问题,我只是找不到答案。这一次,我想知道,为什么成员方法工作。特别是成员方法中的while循环。那么,为什么下面的代码可以工作:
while(current){
if(current->i==a){
return 1;
}
...
}为什么论点while(current)不产生无限的执行?
这是整个节目:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct liste{
int i;
struct liste *next;
};
struct liste *m [4];
struct liste *current;
int hash(int b){
printf("%i\n",sizeof(m));
return b%sizeof(m);
}
int insert(int a){
struct liste *new = malloc(sizeof(struct liste));
if(new){
new->i = a;
new->next=m[hash(a)];
m[hash(a)] = new;
return 1;
}
return 0;
}
int member(int a){
current = m[hash(a)];
while(current){
if(current->i==a){
return 1;
}
current = current->next;
}
return 0;
}发布于 2015-07-10 18:26:03
您的第一个代码片段并不涵盖所有的循环:
while(current) {
if(current->i==a) {
return 1;
}
current = current->next; // Important!
} // this is the end of the loop's body循环中的最后一条语句更改了current的值。最终,它将是NULL,也就是循环结束时。
看来你的问题更多的是关于为什么
// ...
current = m[hash(a)];
while(current){
// ...即使m的元素没有显式初始化为NULL,也可以工作。正如另一个答案的注释所指出的,原因是全局值与局部变量相反,是默认初始化的。
我想补充的是,IMHO --目前形式的代码--写得不好。因为这实际上是一个哈希表,所以应该将其打包到在某些struct hashtable上操作的函数中,而不是一些全局变量。
发布于 2015-07-10 18:27:02
您必须考虑完整的while循环:
while(current){
if(current->i==a){
return 1;
}
current = current->next;
}只要if的条件是假的,current就会在while循环的每个循环中被修改。
此外,如果a不在列表中,则在搜索整个列表后,current将变成NULL (或0)。然后while循环将终止,因为它的条件被求值为false。
注意:在您的程序中,数组m是一个全局变量。Global variables are always initialized to 0。数组元素的初始值在下面的行中复制到next函数中的insert()指针:
new->next=m[hash(a)];因此,列表中的最终next将始终为0。
https://stackoverflow.com/questions/31347719
复制相似问题