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,

  1. 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 exceeded realloc() account allocating enough space prevent realloc()ing again quickly.

  2. always check return value of scanf() or end invoking undefined behavior , program behave in undefined manner.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -