#Defining the type of a dynamic array

7 messages · Page 1 of 1 (latest)

rain moat
#

I've got a group of functions that can create, insert into, and free() a dynamic array, but I've run into a problem where I need two different data types for separate arrays.

Would it be possible, in initArray() and insertArray() to pass an argument that literally holds a data type (char, int, etc..) that way I don't have to define multiple functions?

// struct for dynamic array
typedef struct ArrayStruct {
    char *array;
    size_t used;
    size_t size;
} Array;

// create the array
void initArray(Array *a, size_t initialSize)
{
    a->array = malloc(initialSize * sizeof(char));
    a->used = 0; // number of entries
    a->size = initialSize;
}

// insert elements into the array
void insertArray(Array *a, char element) 
{
    // a->array[a->used++] updates a->used after the array has been accessed
    // so a->used can go up to a->size
    if (a->used == a->size) {
        a->size *= 2;
        a->array = realloc(a->array, a->size * sizeof(char));
    }
    a->array[a->used++] = element;
}

// free memory allocated to the array after done
void freeArray(Array *a)
{
    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}
high cliffBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

fiery lily
#

No.

#

(C++'s templates also just create one implementation for each type.)

rain moat
#

Ah bummer

#

Thank you

#

!solved