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

前端 未结 2 398
陌清茗
陌清茗 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 <stdbool.h>
    
    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 <stdbool.h>
    #include <stdlib.h>
    #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 <stdio.h>
    #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.

    0 讨论(0)
  • 2020-12-21 05:17

    You have all the right to say:

    typedef struct Node *NodePtr;
    struct List
    {
        NodePtr front;    
    };
    

    this typedef struct Node *NodePtr; is a forward declaration. You can use it for as long as you use pointers to types. Pointers need no knowledge about the type's (classes) structure. And the compiler is happy.

    0 讨论(0)
提交回复
热议问题