当前位置: 首页 > 工具软件 > Snippet > 使用案例 >

c snippet 1

江礼骞
2023-12-01

some usage of pointer to pointer:

1.create a list
struct list
{
  void *data;
  struct list *next;
};

struct list *list_new(void *x,...)
{
  va_list ap;
  struct list *list, **p = &list;

  va_start(ap, x);
  for (; x; x = va_arg(ap, void *))
  {
    *p = calloc(sizeof(**p));
    (*p)->data = x;
    p = &(*p)->next;  
  }
  *p = NULL;
  va_end(ap);
  return list;
}

2.traverse a list
struct list *list_append(struct list *list, struct list *tail)
{
  struct list **p = &list;
  while (*p)
    p = &(*p)->next;
  *p = tail;
  return list;
}

3.remove an element from a list
void list_remove(struct list *list, void *x)
{
  struct list *q, **p = &list;
 
  for (; (*p) && (*p)->data != x; p = &(*p)->next)
    ;
  if (*p != NULL)
  {
    q = *p;
    *p = (*p)->next;
    free(q);
  }
}

 类似资料:

相关阅读

相关文章

相关问答