I have a text file with variable length lines which I would like to store in a dynamic array using c.
The following is the dynamic array implementation:
struct array {
char **elements;
long size;
long capacity;
};
void array_init(struct array *array, long capacity)
{
array->capacity = capacity;
array->elements = malloc(capacity * sizeof(char*));
}
void array_push_back(struct array *array, char *element)
{
if (array->size == array->capacity) {
array->capacity *= 2;
array->elements = realloc(array->elements, array->capacity * sizeof(char*));
}
array->elements[array->size++] = element;
}
I read the file via the following:
struct array array;
FILE *file = fopen(filename, "r");
const unsigned MAX_LENGTH = 256;
char buffer[MAX_LENGTH];
array_init(&array, 1000);
while (fgets(buffer, MAX_LENGTH, file))
{
array_push_back(&array, buffer);
}
for (int i = 0; i < array.size; i++)
{
printf(array.elements[i]);
}
printf
prints the last element only as many times as large the array is. I guess it is because I assign buffer
's address to array.elements[i]
and only change the content of buffer
.
Can someone please help with correctly reading from a file and storing it?