C语言报错‘variable-sized object may not be initialized’求助
Hey there! Let's work through the issues you're seeing with your C code step by step.
First, Let's Break Down the Errors
1. error: variable-sized object may not be initialized
Even though you marked rows and columns as const, in C these are still runtime variables—not compile-time constants. When you use variables to define an array's dimensions, you create a Variable-Length Array (VLA). The C standard explicitly forbids initializing VLAs when you declare them, because the compiler can't know the array's exact size at compile time to set up the initial values properly.
2. "Array initialization elements too many" warning
This is actually a side effect of the first error. The compiler gets confused by the invalid initialization of a VLA, so it misinterprets your initializer list and throws this warning. Fix the first error, and this warning will disappear automatically.
Solutions to Fix Your Code
Here are two straightforward ways to resolve these issues:
Option 1: Use Compile-Time Constants (Simplest for Fixed Sizes)
Replace your const variables with #define macros. Macros are resolved at compile time, turning your array into a fixed-size structure that can be initialized normally:
#include<stdio.h> #define rows 2 #define columns 3 int main() { int grades[rows][columns] = { {12, 23, 45}, {64, 78, 89} }; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { printf("%d ", grades[i][j]); } } return 0; }
Option 2: Declare the VLA First, Then Manually Assign Values
If you need to keep rows and columns as runtime variables (e.g., their values might change later), you can declare the VLA without initialization, then assign each element individually:
#include<stdio.h> int main() { int const columns = 3; int const rows = 2; int grades[rows][columns]; // Declare VLA without initialization // Manually assign values to each element grades[0][0] = 12; grades[0][1] = 23; grades[0][2] = 45; grades[1][0] = 64; grades[1][1] = 78; grades[1][2] = 89; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { printf("%d ", grades[i][j]); } } return 0; }
Quick Note
If you ever need a truly dynamic array (size determined at runtime and potentially large), you'd use malloc() to allocate memory on the heap, but for your current use case, one of the above options should work perfectly.
内容的提问来源于stack exchange,提问作者Camille




