I was trying to find out the reason why arrays have static size in C, and so far I know that dynamic allocation can impact how long it takes for code to execute. Also, I know that another reason would be that its size needed to be fix in compile time, but here comes the problem: What happens when I have something like
int n;
scanf("%d", &n);
int arr[n];
What's the difference if my array size were a static value, just like
int arr[3];
CodePudding user response:
What's the difference if my array size were a static value ... like
int arr[3]?
You'll notice the difference when someone types in "1234567890", in which case the variable-length array will overflow the stack. Of course, if you try to define an overly large static array, you'll also get a stack overflow.
The performance question surely can't matter, since any code in which you parse formatted I/O is not going to be in your performance-critical tight loop. If you were to get n from a function parameter, then there are probably cases where the compiler's ability to know the size of your data could impact its ability to apply various optimizations. For example, if you were to call memset() on your fixed-size array, the compiler might well be able to replace that with one or a few machine instructions rather than the full code of memset(), efficient though it might be.
CodePudding user response:
int arr[n]; it is not dynamic allocation. Dynamic allocation happens when you use malloc family of functions.
What's the difference if my array size were a static value, just like
int arr[3];
There is almost no difference from the performance perspective (a few more machine code instructions.
Bear in mind that VLAs can be only defined in the function (or more general block) scope (ie they have to have automatic storage duration). They cannot also be initialized when defined.
CodePudding user response:
In this code snippet
int n;
scanf("%d", &n);
int arr[n];
there is declared a variable length array. Its size is determined at run-time according to the entered value of the variable n.
Pay attention to that the value of the variable n shall be greater than zero.
You may not initialize such an array in its declaration. And such an array may be declared only in a block scope. That is the array shall have automatic storage duration.
In this declaration
int arr[3];
there is declared an array with a fixed size. You may initialize it in its declaration like for example
int arr[3] = { 0 };
Such an array may be declared in a file scope or a block scope.
