首页 > 解决方案 > 制作可用于不同大小结构的通用链表实现

问题描述

嗨,我目前正在做一个项目,我正在创建一个非常简单的文件系统,并且我正在研究一些 inode 和通用文件缓存实现,我想知道考虑这样的结构:

typedef struct disk_inode {
  short type; /* file type */
  short nlinks; /* number of directory entries referring to this file
  int size;    /* file size in bytes */
  short inode_indir_idx;
  /* pointers to the first NDIRECT blocks */
  blknum_t direct[INODE_NDIRECT];
  blknum_t indirect; /* The rest of the blocks */ 
}disk_inode_t;


struct cache{
    short blocknr;
    char block[512];
};

有没有办法创建一个可供这两种结构使用的通用列表?这是在 C 中,我不能使用任何标准的 c 库。

标签: clinked-list

解决方案


void *您可以创建一个将 a作为其元素的通用链表。但是,在大多数情况下,这种实现需要您分配元素。

这是一个简单的例子:

typedef struct list_s
{
    void *elm;
    struct list_s *next;
    struct list_s *prev;
} list_t;

typedef struct
{
    int elem1;
    int elem2;
    int elem3;
} my_struct_t;

int main(void)
{
    my_struct_t *elem = malloc(sizeof(my_struct_t));
    list_t *list = malloc(sizeof(list_t));

    list->prev = NULL;
    list->next = NULL;
    list->elm = elem;
    return 0;
}

推荐阅读