Expand array of 1 element every loop C -
i have let user how many inputs wants , every loop need expand array let others input, when n=-1
need end loop.
this code:
void extend(int *a) { int *pt; pt = (int*) realloc(a , sizeof(int)); } int main() { int *a; = (int*)malloc(sizeof(int)); int i=0; int n=0; while(n!=-1) { scanf("%d", &n); if(n != -1) { a[i] = n; extend(a); i++; } } return 0; }
it works 3 values stops working, can loop want when n
become -1
crashes. have "invalid next size" error in compiler.
edit:
this code works:
int main() { int *a = (int*)malloc(0); int i=0; int n; { scanf("%d", &n); if(n!=-1) { i++; = (int*) realloc(a , i*sizeof(int)); a[i-1] = n; } } while(n!=-1); return 0; }
the imporant mistake don't reassign new realloc()
ed pointer previous pointer , not changing size.
try this
size_t extend(int **original, size_t oldsize) { void *pointer; pointer = realloc(*original, (oldsize + 1) * sizeof(*original); if (poitner == null) return oldsize; *original = pointer; return oldsize + 1; }
and in main()
size_t size; int *data; int number; data = malloc(sizeof(int)); if (data == null) return -1; size = 1; while ((scanf("%d", &number) == 1) && (number != -1)) { data[size] = number; size = extend(data, size); }
also note,
allocating memory expensive in terms of cpu usage, might want avoid doing every element. perhaps define
struct
hold size , capacity (an estimate of how many integers might there) , when capacity exceededrealloc()
account allocating enough space preventrealloc()
ing again quickly.always check return value of
scanf()
or end invoking undefined behavior , program behave in undefined manner.
Comments
Post a Comment