-1

I can't post my actual code because this is for a homework assignment and I don't want to risk cheating, I can give an example of my issue though. For example this is a version of what I'm trying to do, creating an array with a parameter.

void func(int length)
{
    int array[length] = {0};
}

This is oversimplified but it is stating that I can't do this and I receive this error:

Problem-01FAILED.c:48:16: error: variable-sized object may not be initialized int tempArray[t][2] = {}; ^ 1 error generated.

It also stated that I can't do the below, assign the value of the parameter to a variable and create an array within the function using that. It gives the same error.

void func(int length)
{
    int t = length;
    int array[t] = {0};
}

If anyone can tell me why this is happening and how to fix it, I would greatly appreciate it.

ipefaur
  • 49
  • 4
  • The error is pretty clear, no? This is a VLA (variable length array) and it cannot be initialized by the C rules. – Eugene Sh. Nov 03 '20 at 21:44
  • 1
    What happens to the memory where `array[t]` is stored when the function returns? (Hint: Poof!) – David C. Rankin Nov 03 '20 at 21:45
  • 2
    Without looking at any docs, I see that the error message is telling us that you're not allowed to initialize the array the same way you would a constant length array. You have to have to use a loop (or `memset`) to fill it with zeros. – luther Nov 03 '20 at 21:45
  • 1
    Does this answer your question? [C compile error: "Variable-sized object may not be initialized"](https://stackoverflow.com/questions/3082914/c-compile-error-variable-sized-object-may-not-be-initialized) – Aykhan Hagverdili Nov 03 '20 at 21:51

1 Answers1

0

The size of the array is not known until runtime, i.e. it is a variable length array (VLA), and because of that it cannot be initialized.

If you want to set all values to 0, you can use memset:

memset(array, 0, sizeof(array));
dbush
  • 205,898
  • 23
  • 218
  • 273
  • RE “because of that it cannot be initialized”: That is overly simplified. A variable length array could be initialized: We can easily write the source code to do that, and a compiler could easily generate it. The C standard committee decide not to provide that feature. I do not know why, but it means that the reason is not simply “because it is a variable length array.” It is also because C 2018 6.7.9 says the entity to be initialized shall not be a variable length array type, and that in turn is because of some reasons the committee must have had. – Eric Postpischil Nov 03 '20 at 22:05