Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C] ArrayList
#1
arraylist.c
Code:
#include <stdlib.h>
#include "arraylist.h"

ArrayList *allocate(ArrayList *list, int capacity)
{
    list->capacity = capacity;
    list->element = malloc(capacity * sizeof(void *));
    list->currentIndex = 0;
    return list;
}

int addElement(ArrayList *list, void *object)
{
    addElementIndex(list, object, list->currentIndex++);
}

int addElementIndex(ArrayList *list, void *object, int index)
{
    if (index < 0 || index > list->currentIndex)
        return 0;
    if (list->currentIndex >= list->capacity)
    {
        if (realloc(list->element, list->capacity * 2) == NULL)
            return 0;
        list->capacity *= 2;
    }
    list->element[index] = object;
    return 1;
}

void *getElement(ArrayList *list, int index)
{
    return list->element[index];
}

void *removeElement(ArrayList *list, int index)
{
    if (index < 0 || index > list->currentIndex)
        return 0;
    void *object = list->element[index];
    int i;
    for (i = index; i < list->currentIndex; i++)
        list->element[i] = list->element[i + 1];
    list->currentIndex--;
    return object;
}

int getSize(ArrayList *list)
{
    return list->currentIndex;
}

int isEmpty(ArrayList *list)
{
    return list->currentIndex == 0;
}

void clearAll(ArrayList *list)
{
    int i;
    for (i = 0; i < list->currentIndex; i++)
        list->element[i] = NULL;
    list->currentIndex = 0;
}

void destroyArrayList(ArrayList *list)
{
    free(list->element);
}

arraylist.h
Code:
#ifndef _STACK_H
#define _STACK_H

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
    int currentIndex;
    int capacity;
    void **element;
} ArrayList;

ArrayList *allocate(ArrayList *, int);
int addElement(ArrayList *, void *);
int addElementIndex(ArrayList *, void *, int);
void *getElement(ArrayList *, int);
void *removeElement(ArrayList *, int);
int getSize(ArrayList *);
int isEmpty(ArrayList *);
void clearAll(ArrayList *);
void destroyArrayList(ArrayList *);

#ifdef __cplusplus
}
#endif

#endif /* _STACK_H */

Constructive criticism appreciated as im still learning.
My SMF Modifications:
http://anthony.vibrantvps.com/smf
Reply
#2
Not bad. But one major thing I recommend is to do some type checking and what not.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)