c - malloc and realloc size of integer array -


i want able realloc amount of space program reads in numbers. example when running should able read number of integer , print them out 'int array: (all inputs)' have tried far:

int main(int argc, char **argv) {     int = 0, n, num;     int *a;      = malloc(sizeof(a));      while(scanf("%d",&num) == 1)     {         a[i] = num;         i++;     }      n = sizeof(a)/sizeof(a[0]);      printf("int array: ");     (i = 0; < n; i++)     {         printf("%d ", a[i]);     }      return 0; } 

you first reserve specific amount of memory i.e: if user inputs more 10 items realloc block of memory of 20 integers , copy last 10 items new block , on.

size_t block_length = 10; size_t current_length = 0; int *a = malloc(sizeof(int) * block_length); // store 10 integer if (a == null)     donotcontinue_allocationfailure(); current_length += block_length; // ... input first ten numbers, check if count numbers lesser // block_length void *ptr; ptr = realloc(a, sizeof(int) * (block_length + current_length) if (ptr == null)  {     free(a); /* otherwise memory leak occurs */     donotcontinue_allocationfailure();  } = ptr;  // can hold 20 numbers, , can input next 10 numbers 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -