简体   繁体   English

在 C 中处理空指针

[英]Handling void pointers in C

I'm making a C code to handle sparse matrixes, and i want to modularize my code at its maximum.我正在编写一个 C 代码来处理稀疏矩阵,我想最大限度地模块化我的代码。

I noticed that there are a couple times when i need to walk-until-i-find-the-previous-node (oh, i am using linked lists to build the matrix), and i want to make a reusable function.我注意到有几次我需要遍历直到找到上一个节点(哦,我正在使用链表来构建矩阵),并且我想创建一个可重用的函数。

I have 4 structs in my code, all of them have the vars first , last or next if is a child structure that have no header-role.我的代码中有 4 个结构,如果是没有标头角色的子结构,它们都具有 vars firstlastnext

I thought a code like this:我想到了这样的代码:

void *iterateUntilNext(void *header, void *child)
{
    void *walker = header->first;
    while (walker->next != child)
    {
        walker = walker->next;
    }
    return walker;
}

But i got this error: expression must have pointer-to-struct-or-union type but it has type "void *"但是我收到了这个错误: expression must have pointer-to-struct-or-union type but it has type "void *"

Is there any way to make this work or am i dreaming too much?有什么办法可以使这项工作成功还是我做梦太多了?

OOP面向对象编程

Define a base struct like定义一个基本结构,如

#define list_item_interface \
  list_item *first; \
  list_item *next;

typedef struct list_item {
    list_item_interface
} list_item;

and 'derive' your custom items like并“派生”您的自定义项目,例如

typedef struct custom_list_item {
    list_item_interface //needs to be the first entry
    //other members/fields
} custom_list_item;

then define your 'generic' functions like然后定义您的“通用”功能,例如

list_item* iterate(list_item *header, list_item *child) { /*...*/ }

call it like称之为

custom_list_item *header, *child;
iterate((list_item*) header, (list_item*) child);

GCC - Extension GCC - 扩展

Accepts any type, which provides the fields first and next of the same type.接受任何类型,它提供相同类型的firstnext字段。

#define LIST_ITEM_ITERATE(HEADER, CHILD) ({ \
    __auto_type HEADER_ = (HEADER); \
    __auto_type CHILD_  = (CHILD); \
    __auto_type WALKER  = HEADER_->first; \
    while (WALKER->next != CHILD_) \
        WALKER = WALKER->next; \
    WALKER; \
)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM