C错误“可能无法初始化可变大小的对象”

可能重复:
C编译错误:“可能无法初始化可变大小的对象”

我有一个问题,因为我的编译器仍然给我一个错误:可能无法初始化变量大小的对象。 我的代码出了什么问题?

int x, y, n, i; printf ("give me the width of the table \n"); scanf ("%d", &x); printf ("give me the height of the table\n"); scanf ("%d", &y); int plansza [x][y] = 0; int plansza2 [x][y] = 0; 

当然我想用“零”填充表格。

不幸的是,该计划仍然无效。 这些表格在所有单元格中显示为“416082”等数字。 我的代码现在看起来像这样:

 int plansza [x][y]; memset(plansza, 0, sizeof plansza); int plansza2 [x][y]; memset(plansza2, 0, sizeof plansza2); printf("plansza: \n"); for(j=0;j<x;j++) { for(l=0;l<y;l++) { printf("%d",plansza[x][y]); printf(" "); } printf("\n"); } printf("plansza2: \n"); for(m=0;m<x;m++) { for(o=0;o<y;o++) { printf("%d",plansza2[x][y]); printf(" "); } printf("\n"); } 

你的两个数组是可变长度数组 。 您无法在C中初始化可变长度数组。

要将数组的所有int元素设置为0 ,可以使用memset函数:

 memset(plansza, 0, sizeof plansza); 

顺便初始化一个不是可变长度数组的数组,将所有元素初始化为0的有效forms是:

 int array[31][14] = {{0}}; // you need the {} 

如果两个维度都是未知的,则必须使用一维数组,并自行编制索引:

 int *ary = (int *) malloc(x * y * sizeof(int)); memset(ary, 0, x * y * sizeof(int)); int elem1_2 = ary[1 * x + 2]; int elem3_4 = ary[3 * x + 4]; 

等等。 您最好定义一些宏或访问函数。 并在使用后释放内存。

替代@Chris的建议:

您可以将二维数组创建为一维数组的数组。 这将允许您像以前一样进行数组元素索引。 请注意,在这种情况下,数组是在堆中分配的,而不是在堆栈中。 因此,当您不再需要该arrays时, 必须清除已分配的内存。

例:

 #include  #include  /* Create dynamic 2-d array of size x*y. */ int** create_array (int x, int y) { int i; int** arr = (int**) malloc(sizeof (int*) * x); for (i = 0; i < x; i++) { arr[i] = (int*) malloc (sizeof (int) * y); memset (arr[i], 0, sizeof (arr[i])); } return arr; } /* Deallocate memory. */ void remove_array (int** arr, int x) { int i; for (i = 0; i < x; i++) free (arr[i]); free (arr); } int main() { int x = 5, y = 10; int i, j; int** plansza = create_array (x, y); /* Array creation. */ plansza[1][1] = 42; /* Array usage. */ remove_array (plansza, x); /* Array deallocation. */ return 0; }