Skip to content

Instantly share code, notes, and snippets.

@nmabhinandan
Last active January 13, 2017 10:44
Show Gist options
  • Save nmabhinandan/5fbcb280382eac042abe7ab163d02f97 to your computer and use it in GitHub Desktop.
Save nmabhinandan/5fbcb280382eac042abe7ab163d02f97 to your computer and use it in GitHub Desktop.
Integer array implementation in C
#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