C语言指针域内存什么,c语言queue--数据域与指针域分开

实现:

#ifndef HO_QUEUE_H

#define HO_QUEUE_H

#include 

#undef offsetof

struct queue_head {

struct queue_node *head;

struct queue_node *tail;

};

struct queue_node {

struct queue_node *next;

};

#define QUEUE_HEAD_INIT {.head = NULL, .tail = NULL}

#define INIT_QUEUE_HEAD(ptr) do {\

(ptr)->head = NULL;(ptr)->tail = NULL; \

} while (0)

#define offsetof(type, member) ((size_t)&((type *)0)->member)

#define queue_entry(ptr, type, member) (type *)((char *)ptr - offsetof(type, member))

static inline void queue_put(struct queue_node *n, struct queue_head *h) {

n->next = NULL;

if (!h->head) {

h->head = h->tail = n;

} else {

h->tail->next = n;

h->tail = n;

}

}

static inline struct queue_node *queue_get(struct queue_head *h) {

struct queue_node *t = h->head;

h->head = h->head ? h->head->next: NULL;

return t;

}

static inline int queue_empty(struct queue_head *h) {

return !h->head;

}

#define queue_for_each(pos, h) \

for(pos = (h)->head; pos; pos = pos->next)

#endif

如何使用:

#include 

#include 

#include 

#include "queue.h"

struct queue_node2 {

void *data;

struct queue_node queue;

};

int main() {

struct queue_head head = QUEUE_HEAD_INIT;

struct queue_node *pos;

struct queue_node2 *tmp;

tmp = malloc(sizeof(struct queue_node2));

tmp->data = strdup("aaaaaaaaaaaaaaa");

queue_put(&tmp->queue, &head);

tmp = malloc(sizeof(struct queue_node2));

tmp->data = strdup("bbbbbbbbbbbbbbb");

queue_put(&tmp->queue, &head);

tmp = malloc(sizeof(struct queue_node2));

tmp->data = strdup("ccccccccccccccc");

queue_put(&tmp->queue, &head);

tmp = malloc(sizeof(struct queue_node2));

tmp->data = strdup("ddddddddddddddd");

queue_put(&tmp->queue, &head);

#if 0

queue_for_each(pos, &head) {

tmp = queue_entry(pos, struct queue_node2, queue);

printf("%s\n", (char *)tmp->data);

}

#endif

while (!queue_empty(&head)) {

pos = queue_get(&head);

tmp = queue_entry(pos, struct queue_node2, queue);

printf("%s\n", (char *)tmp->data);

free(tmp->data);

free(tmp);

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值