C programming. How to hide implementation of the struct in .c if I need to refer to its instance in header file (.h)

前端 未结 2 397
陌清茗
陌清茗 2020-12-21 04:19

So I am curious how to hide implementation of the struct in .c file if we need to refer to its instance in header file. For example I have the following struct in header fil

2条回答
  •  失恋的感觉
    2020-12-21 05:13

    Something like this should work fine. Note that the definition of struct Node never leaves List.c.

    list.h

    #pragma once
    #include 
    
    struct List {
        struct Node *front;
    };
    
    void list_init(struct List **list);
    void list_free(struct List *list);
    void list_insert(struct List *list, void *value);
    bool list_contains(struct List *list, void *value);
    

    list.c

    #include 
    #include 
    #include "list.h"
    
    struct Node {
        void *value;
        struct Node *next;
    };
    
    void list_init(struct List **list) {
        *list = malloc(sizeof(**list));
    }
    
    void list_free(struct List *list) {
        struct Node *node = list->front;
        while (node != NULL) {
            struct Node *next = node->next;
            free(node);
            node = next;
        }
        free(list);
    }
    
    void list_insert(struct List *list, void *value) {
        struct Node *node = malloc(sizeof(*node));
        node->value = value;
        node->next = list->front;
        list->front = node;
    }
    
    bool list_contains(struct List *list, void *value) {
        struct Node *node;
        for (node = list->front; node != NULL; node = node->next)
            if (node->value == value)
                return true;
        return false;
    }
    

    main.c

    #include 
    #include "list.h"
    
    int main() {
        struct List *l;
        list_init(&l);
    
        int *value_1 = malloc(sizeof(int));
        int *value_2 = malloc(sizeof(int));
        int *value_3 = malloc(sizeof(int));
    
        list_insert(l, value_1);
        list_insert(l, value_2);
        list_insert(l, value_3);
    
        printf("Does the list contain value_1: %d\n", list_contains(l, value_1));
        printf("Does the list contain null:    %d\n", list_contains(l, NULL));
    
        list_free(l);
        return 0;
    }
    

    It's very possible that I have some errors in this code. If you see any, feel free to fix them.

提交回复
热议问题