我又遇到了一个非常愚蠢的问题,我就是找不到答案。这次我想知道为什么成员方法有效。尤其是成员方法中的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;
}
最佳答案
你必须考虑完整的 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 .数组元素的初始值被复制到以下行中 insert()
函数中的 next
指针:
new->next=m[hash(a)];
因此,列表中最后的 next
将始终为 0。
关于C的怪异指针运算2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347719/