-
-
Save thiagorock22/2b9610dc83392f089d3e9d68634cb9e8 to your computer and use it in GitHub Desktop.
Example of structure encapsulation in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment