C的怪异指针运算2

标签 c pointers struct

我又遇到了一个非常愚蠢的问题,我就是找不到答案。这次我想知道为什么成员方法有效。尤其是成员方法中的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/

相关文章:

C - 在位图中绘制

c - main() 前后的函数声明

c - a 和 b 之间所有数字的和

c++如何将指针分配给二叉树中的父节点

c++ - 从智能指针获取原始指针

c - 在 C 中将 char 数组作为参数传递为指针

c - 使用十六进制数

c - 将结构数组分配给指针

c# - 当我有一个双倍结构时,为什么我的结构会出现意外的大小?

c - 使用 C 将二进制文件读入结构体,处理 char [8]