Last active
January 13, 2017 10:44
-
-
Save nmabhinandan/5fbcb280382eac042abe7ab163d02f97 to your computer and use it in GitHub Desktop.
Integer array implementation 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 <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
typedef struct __array__ | |
{ | |
int* data; | |
int capacity; | |
int size; | |
int max; | |
int min; | |
} Array; | |
void initArray(Array* array, int capacity) { | |
(*array).data = (int*)malloc(capacity * sizeof(int)); | |
(*array).size = 0; | |
(*array).capacity = capacity; | |
} | |
void insertIntoArray(Array* array, int value) { | |
int* ptr = (*array).data; | |
if (((*array).size + 1) > (*array).capacity) { | |
return; | |
} | |
if ((*array).size > 0) { | |
ptr += (*array).size; | |
} else { | |
(*array).max = value; | |
(*array).min = value; | |
} | |
(*array).max = (value > (*array).max) ? value : (*array).max; | |
(*array).min = (value < (*array).min) ? value : (*array).min; | |
*ptr = value; | |
(*array).size++; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
Array a1; | |
initArray(&a1, 10); | |
insertIntoArray(&a1, 2); | |
insertIntoArray(&a1, 3); | |
insertIntoArray(&a1, 1); | |
insertIntoArray(&a1, 5); | |
insertIntoArray(&a1, 8); | |
assert(a1.max == 8); | |
assert(a1.min == 1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment