0
#include<stdio.h>
int main(){
    int s;
    scanf("%d",&s);//taking s as user input
    int arr[s];//s not a constant
    for(int i=0;i<s;i++){
        scanf("%d",&arr[i]);
    }
    printf("\nyou entered the array: \n");
    for(int i=0;i<s;i++){
        printf("%d ",arr[i]);
    }
    return 0;
}

As I knew while declaring an array size it should be a constant.

  • 5
    It's called VLA (variable length array) and it has been introduced in the C99 standard (that's more than 20 years ago). So your program is perfectly legal (and correct) as per the C99 standard – Jabberwocky Oct 20 '22 at 13:14
  • OTOH beware of large VLAs because on most platforms VLSs are stored on the stack which has limited space. Typical default values: 8 Mb on Linux and only 1Mb on Windows. If you exceed the available space, the behaviour is undefined, most likely your program will crash. – Jabberwocky Oct 20 '22 at 13:57
  • Even though it's called a *variable* length array, you can't change the size once it's been defined. It's "variable" in the sense that its size can be different each time it's created, but once created it cannot be resized. – John Bode Oct 20 '22 at 14:25

1 Answers1

0

As per Jabberwocky's comment to the question, what you are referring to is a feature of C called variable-length arrays. To quote this cppreference.com's page:

If expression is not an integer constant expression, the declarator is for an array of variable size.

Each time the flow of control passes over the declaration, expression is evaluated (and it must always evaluate to a value greater than zero), and the array is allocated (correspondingly, lifetime of a VLA ends when the declaration goes out of scope). The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.

This feature was added to the language in the C99 standard (again, as per Jabberwocky's comment. See also https://en.cppreference.com/w/c/99 , section "New language features").

Speaking more generally, the size of an array may be not constant. To quote this cppreference.com's page again:

There are several variations of array types: arrays of known constant size, variable-length arrays, and arrays of unknown size.

As a side note, Jabberwocky mentioned in comments that VLAs may be allocated on the stack. For more information on this, you may see this question: Is it required that a C Variable Length Array is allocated from the stack?

user20276305
  • 95
  • 1
  • 7