Created
February 1, 2017 20:31
-
-
Save bentrevett/715a0814f6552ab5822cd6be432e010d to your computer and use it in GitHub Desktop.
Example of OOP in C.
This file contains 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
#include <stdlib.h> | |
#include <stdio.h> | |
typedef struct Array { | |
int* arr; | |
size_t length; | |
} Array; | |
Array* newArray(int len) | |
{ | |
Array* ptr = malloc(sizeof(Array)); | |
ptr->arr = malloc(sizeof(int) * len); | |
ptr->length = len; | |
return ptr; | |
} | |
void deleteArray(Array* obj) | |
{ | |
free(obj->arr); | |
free(obj); | |
} | |
void assign(Array* obj, size_t index, int x) | |
{ | |
if (index > obj->length) | |
return; | |
else | |
obj->arr[index] = x; | |
} | |
int getNum(Array* obj, size_t index) | |
{ | |
if (index > obj->length) | |
return 0; | |
else | |
return obj->arr[index]; | |
} | |
int main() | |
{ | |
size_t i; | |
Array* arr = newArray(10); | |
for (i = 0; i < arr->length; i++) { | |
assign(arr, i, i * 100); | |
} | |
for (i = 0; i < arr->length; i++) { | |
printf("%d\n", getNum(arr, i)); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment