Search code examples
cdynamic-memory-allocationreallocfunction-definition

how to expand an array based on user input in c


Im trying to write a program that asks the user for the size of an array and if they are asked again then the size of the array would increase based on the number they input.

int main()
{
   int size;
   int n;
   printf("Size of array: ");
   scanf("%d", &n);
   int *ptr = (int*)malloc(n*sizeof(int));
   size = n;
   int n1;  
   do {
       printf("Input the increase size of the array: ");
       scanf("%d", &n1);
       size += n1;
       int *ptr = realloc((size)*sizeof(int));
   } while (n1 != -1);

  return 0;
}


Here is what I have got but how can I move this into a function


Solution

  • For starters this call of the function realloc

    int *ptr = realloc((size)*sizeof(int));
    

    is incorrect. The function expects two arguments.

    If you want to write a function that changes the size of a dynamically allocated array then it can look the following way

    int resize( int **a, size_t n )
    {
        int *tmp = realloc( *a, n * sizeof( int ) );
    
        if ( tmp != NULL ) *a = tmp;
    
        return tmp != NULL;
    } 
    

    and the function can be called for example like

    do {
        n1 = -1;
        printf("Input the increase size of the array: ");
        scanf("%d", &n1);
    } while ( n1 != -1 && resize( &ptr, size += n1 ) );