I am trying to implement a generic array list in C. However, when the data type is any type other than int, the list wont contain the correct data. For example, like 123.1234 as a double, when the double is passed into the list, it will become 000.0000. One when the data type is int, it will have correct value. I don't know which part of the code is wrong, can anyone give me a hint? Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "genericADT.h"
struct list_type {
void *data;
int elementSize;
int size;
int capacity;
};
ListType create(int elementSize) {
ListType listptr = malloc(sizeof(struct list_type));
if (listptr != NULL) {
listptr->size = 0;
listptr->capacity = 10;
listptr->elementSize = elementSize;
listptr->data = malloc(10 * (listptr->elementSize));
if (listptr->data == NULL) {
free(listptr);
listptr = NULL;
}
}
return listptr;
}
void push(ListType listptr, void *item) {
if (listptr->size >= listptr->capacity) {
void *temp = realloc(listptr->data, listptr->elementSize * (listptr->capacity + 100));
if (temp != NULL) {
listptr->capacity += 100;
listptr->data = temp;
memcpy(listptr->data + (listptr->size) * (listptr->elementSize), item, sizeof(listptr->elementSize));
listptr->size++;
}
} else {
memcpy(listptr->data + (listptr->size) * (listptr->elementSize), item, sizeof(listptr->elementSize));
listptr->size++;
}
}
void *get(ListType listptr, int index) {
return listptr->data + index * (listptr->elementSize);
}
int size_is(ListType listptr) {
return listptr->size;
}
sizeof(listptr->elementSize)? Really?malloc()returns a pointer, why are you assigning a pointer tolistptr?void*to the actual data. Then the program that is using that list it can interpret the data in what ever manner fits the application.