Reputation: 277
Starting out with dynamic arrays in C. I am getting an access violation when in the insertArray function (either in the realloc line or when trying to store the element (char) in the array.
Can't seem to work around it or get to the bottom of it. Thanks
Code:
#include <stdio.h>
typedef struct {
char *array;
size_t used;
size_t size;
} Array;
Array elements;
void initArray(Array *a, size_t initialSize) {
a->array = (char *)malloc(initialSize * sizeof(char));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, char element) {
if (a->used == a->size) {
a->size *= 2;
a->array = (char *)realloc(a->array, a->size * sizeof(char));
}
a->array[a->used++] = element;
}
void popArray(Array *a) {
a->used--;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
char vars[15];
int main() {
initArray(&elements, 2);
printf("Enter 15 character String: ");
scanf_s("%s", vars, 15);
for (int i = 0; i < 15; i++) {
insertArray(&elements, vars[i]);
}
freeArray(&elements);
}
Upvotes: 0
Views: 466
Reputation: 206717
I suspect the problem is caused by the missing #include <stdlib.h>
.
See Do I cast the result of malloc? to understand why you should not cast the return value of malloc
.
Upvotes: 1