【问题标题】:C error "variable-sized object may not be initialized" [duplicate]C错误“可变大小的对象可能未初始化” [重复]
【发布时间】:2012-12-20 15:31:31
【问题描述】:

可能重复:
C compile error: “Variable-sized object may not be initialized”

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

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");
}

【问题讨论】:

  • 你和memset()即将结识。

标签: c arrays


【解决方案1】:

您的两个数组是可变长度数组。您不能在 C 中初始化可变长度数组。

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

memset(plansza, 0, sizeof plansza);

顺便说一下初始化一个不是变长数组的数组,将所有元素初始化为0的有效形式是:

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

【讨论】:

  • 好的。我知道了。那么我应该怎么做才能让用户自定义表格大小呢?有可能吗?
  • @user1828352 你声明了它们但你没有初始化它们:删除= 0 部分。
  • 现在可以了吗?:int plansza [x][y]; memset(plansza, 0, sizeof plansza); int plansza2 [x][y]; memset(plansza2, 0, sizeof plansza2);
【解决方案2】:

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

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];

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

【讨论】:

    【解决方案3】:

    替代@Chris 的建议:

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

    示例:

    #include <malloc.h>
    #include <string.h>
    
    /* 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2019-02-21
      • 2017-03-06
      • 2011-03-06
      相关资源
      最近更新 更多