Skip to content

Instantly share code, notes, and snippets.

@echiesse
Created July 26, 2017 00:30
Show Gist options
  • Save echiesse/97ea3552b4a6d1a89ed1de6805d80199 to your computer and use it in GitHub Desktop.
Save echiesse/97ea3552b4a6d1a89ed1de6805d80199 to your computer and use it in GitHub Desktop.

Revisions

  1. echiesse created this gist Jul 26, 2017.
    60 changes: 60 additions & 0 deletions c_encapsulation.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    /* pair.h */
    #ifndef __PAIR_H__
    #define __PAIR_H__

    typedef struct SPair Pair;

    Pair* createPair(int x, int y);
    void destroyPair(Pair *pair);
    int getX(Pair *pair);


    #endif //** __PAIR_H__ **

    //*******************************************************************************
    /* pair.c */
    #include <stdlib.h>
    #include "pair.h"


    struct SPair
    {
    int x;
    int y;
    };


    Pair *createPair(int x, int y)
    {
    Pair *p = malloc(sizeof(Pair));
    p->x = x;
    p->y = y;
    return p;
    }


    int getX(Pair *p)
    {
    return p->x;
    }


    void destroyPair(Pair *p)
    {
    free(p);
    }


    //*******************************************************************************
    /* program.c */
    #include <stdio.h>
    #include "pair.h"


    int main()
    {
    Pair *a = createPair(1, 2);
    printf("x = %i\n", a->x); // Ilegal access
    printf("x = %i\n", getX(a)); // This is ok !
    destroyPair(a);
    }