I want to understand the difference between initializing a 1D array with a variable for it's size Vs. using just a literal for the size.
In a course I'm following, the instructor spoke about how if we declare an array to have 5 elements but only initialize it with 3 elements, the compiler will initialize the other two elements with 0. So, I tried the following - in the first case, I declare a size
variable.
int size = 5;
int scores[size] = {4, 6, 2};
for (int i = 0; i < size; ++i)
{
printf("%d ", scores[i]);
}
printf("\n\n");
However, running this yields the following error -
variable-sized object may not be initialized
I checked this post but I don't believe I understand why the code works when I just use the constant literal (5) like so -
int data[5] = {4, 6, 2};
for (int i = 0; i < 5; ++i)
{
printf("%d\t", data[i]);
}
printf("\n\n");
The above code outputs the three elements and two zeros just as the instructor mentioned.
My question is what is the difference in the above two code snippets.