1
char a[MAX_NR_DIGITS] = {5, 2, 1, 3, 5, 0, 7, 3, 4, 4};
int sizeA = 10;
char n[MAX_NR_DIGITS] = {5, 2, 6};
int sizeN = 3;

It returns me twice the error: variable-sized object may not be initialized. How can i solve this?

5
  • 2
    What is MAX_NR_DIGITS? Where do you get the errors? Can you please try to a Minimal, Complete, and Verifiable Example and show us? And include the full and complete and unedited error output when building? Commented Oct 24, 2016 at 11:50
  • What development environnment do you use ? Commented Oct 24, 2016 at 11:56
  • 1
    I guess that MAX_NR_DIGITS is not a constant. It's only a guess because you don't tell us what MAX_NR_DIGITS is Commented Oct 24, 2016 at 11:58
  • Obviously it is not an integer constant or the OP wouldn't get that error. Commented Oct 24, 2016 at 12:36
  • MAX_NR_DIGITS is 10^8. I have to calculate a^n and the result can have max 10^8 digits. So MAX_NR_DIGITS is a const int . Commented Oct 24, 2016 at 19:32

1 Answer 1

1

In case those arrays are declared at local scope and MAX_NR_DIGITS is not a compile-time integer constant, C will attempt to create a variable-length array (VLA). This is an array which has its size determined during run-time.

The easiest way to avoid this is, if it was unintentional, is to make sure that MAX_NR_DIGITS is a compile-time constant such as #define MAX_NR_DIGITS 10.

The reason why the code doesn't work when the array is a VLA, is because initializer lists are only used during compile-time. Therefore the C language has a requirement saying that VLAs cannot be initialized.

For a VLA you can easily get around this by assigning the array a value in run-time instead:

memcpy(n,  &(char[3]){5, 2, 6},  3);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.