0

I'm writing a program and I've faced an issue where I cannot set the array size to the user's liking. I know it's a pointer-related issue.

#include <stdio.h>

int main() {
    int length;
    scanf_s("%d", &length);
    int array[length]; //"expression must have a constant value"
}
Veanty
  • 33
  • 5

1 Answers1

1

VLAs are optional and MS compiler does not support them. You need to dynamically allocate the array:

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

after use you need to free it manually

free(array);
0___________
  • 60,014
  • 4
  • 34
  • 74
  • *VLAs are optional...* Not under C99. They must be supported for a compiler to be fully C99-compliant. And it looks like a form of VLAs will also be required in C2X, which will probably wind being called C23. – Andrew Henle Dec 16 '22 at 16:22
  • @AndrewHenle `(Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)` C17 – 0___________ Dec 16 '22 at 22:42
  • @AndrewHenle `__STDC_NO_VLA__ The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types.` C17 – 0___________ Dec 16 '22 at 22:46
  • And all that contradicts "Not under C99" in what way? Depending on the standard compiled under, VLAs can very well be mandatory. – Andrew Henle Dec 17 '22 at 12:56