Search code examples
carraysvariable-length-array

How to define array size based upon number of inputs?


As far as my knowledge, (im a beginner in c) you can define the size of an array provided the user knows how many inputs the user is going to provide. But, how can i define the size of an array based upon number of inputs?

For example, if I have to give 10 numbers as input, then how do i declare an array in such a way that its size is assigned as 10 based upon the count of my input? (i don't know if it is possible but yet i want to find out)


Solution

  • Starting with C99 you can use variable-length arrays. You can declare them as you go, using a size_t variable for its size.

    size_t n;
    printf("How many numbers would you like to enter?\n");
    scanf("%zu", &n);
    int array[n];
    for (size_t i = 0 ; i != n ; i++) {
        printf("Enter number %zu: ", i+1);
        scanf("%d", &array[i]);
    }
    printf("You entered: ");
    for (size_t i = 0 ; i != n ; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    

    Demo.

    Note : This approach works for relatively small arrays. If you anticipate using larger arrays, do not use this approach, because it could lead to undefined behavior (overflowing the automatic storage area). Instead, use malloc and free.