2

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;
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
mr.backy
  • 23
  • 4
  • if you're looking at making a dynamic sized array, I'd recommend reading up on the malloc command. You can use it to allocate exactly the number of elements you need and then loop to add them to your array. Just don't forget to free the memory you allocate – Ryan Fitzpatrick Dec 10 '15 at 22:47
  • What exactly are you having trouble with? You can declare a variable length array like `int array[size_Of_Interval];` or you can dynamically allocate with `malloc`. Then use a loop to fill in the array. – kaylum Dec 10 '15 at 22:48

2 Answers2

2

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 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Before to return from the main:

int *array = malloc(size_of_interval * sizeof(int));

This dynamically allocates the needed amount of memory, returning a pointer to the firts element of an array with size_of_interval length. Afterward you can go through a loop and fill that array:

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

When you end the job with your array, as commented above, you need to free the resource:

free(array);
wiredolphin
  • 1,431
  • 1
  • 18
  • 26