arrayscdynamic-memory-allocationdeclarationvariable-length-array

how to put numbers from interval to array? (C language)


I am looking for this for a while. Can anyone tell me how can I create interval array?

Example: interval = < 4;9 > int array[9-4+1] = {4,5,6,7,8,9}

I would like to insert number from interval to array and than I can work with values in array.

#include <stdio.h>
#include <stdlib.h>

int main ()
    {
    int size_Of_Interval;
    int a;  
    int b;

    printf("Please specify the starting interval value: ");
    scanf("%d", &a);
    printf("Please specify the ending interval value: ");
    scanf("%d", &b);
    size_Of_Interval = (b-a+1); 
    printf("Interval from %d to %d. Interval has %d numbers\n", a, b, size_Of_Interval);

    return 0;
    }

Solution

  • If your compiler supports variable length arrays (VLAs) then you can just write

    int arr[size_Of_Interval];
    
    for ( int i = 0; i < size_Of_Interval; i++ )
    {
        arr[i] = a + i;
    }
    

    Otherwise you should dynamically allocate an array. For example

    int *arr = malloc( size_Of_Interval * sizeof( int ) );
    
    for ( int i = 0; i < size_Of_Interval; i++ )
    {
        arr[i] = a + i;
    }
    

    In this case you will need also to free the array when it will not be needed any more

    free( arr );