c - something wrong with my dynamic array -
while add more 13 element, result seems not correct! code below! when add 12 elements, result
the no.0 0
no.1 1
no.2 2
no.3 3
no.4 4
no.5 5
no.6 6
no.7 7
no.8 8
no.9 9
no.10 10
no.11 11
when add 1 more, result changed lot, have no idea what's going on here:
the no.0 0
no.1 1
no.2 2
no.3 3
no.4 4
no.5 5
no.6 6
no.7 7
no.8 0
no.9 1
no.10 2
no.11 3
no.12 12
#include<stdio.h> #include<stdlib.h> typedef struct dynarray myarray; struct dynarray { int size; int length; int *array; }; myarray *create(void) { /* todo: define arrays */ myarray *da; da = malloc(sizeof(myarray)); da->size = 0; da->length = 3; da->array = (int *)malloc(da->length * sizeof(int)); return da; } void add(myarray *array, int val) { int i; int length = array->length; int size = array->size; int *temp; //printf("da->size1 = %d\nda->length1 = %d\n",array->size,array->length); if (size == length) { temp = (int *)malloc(length * sizeof(int)); (i = 0; i<size; i++) { temp[i] = array->array[i]; printf("%d,", array->array[i]); } //printf("!@#$@#$=%d\n",array->length); array->array = (int*)realloc(array->array, sizeof(int)*length); (i = 0; i<size; i++) array->array[i] = temp[i]; array->length *= 2; length *= 2; } if (size <length) { array->array[size] = val; printf("array[%d]====%d\n", size, array->array[size - 1]); array->size++; } } int main() { int i; myarray *da = create(); //printf("da->size = %d\nda->length = %d\n",da->size,da->length); (i = 0; i<12; i++) add(da, i); // printf("a->size = %d\nda->length = %d\n",da->size,da->length); (i = 0; i<12; i++) printf("the no.%i %d\n", i, da->array[i]); }
as said in comments, you're misusing realloc , not editing length correctly. here's add should be:
void add(myarray *array, int val){ int length = array->length; int size = array->size; if(size == length){ array->length *= 2; array->array=(int*)realloc(array->array,sizeof(int)*length); } array->array[size] = val; array->size++; }
Comments
Post a Comment