【问题标题】:Why do my int values change when assigning them into a malloc array?为什么我的 int 值在分配到 malloc 数组时会发生变化?
【发布时间】:2022-06-10 22:46:18
【问题描述】:

这是我的二维 malloc 数组的初始化:

    int** intArray;
    intArray=malloc(rows*sizeof(int*));
    for(i=0;i<rows;i++)
    intArray[i]=malloc(columns*sizeof(int*));

这是我更改二维数组中现有值的地方,但所有值都更改为 0,即使某些值不是 0。getLiveNeighbours 和 decisionDeadorALive 是具有 int 返回类型的方法。

int r, c;

for(r=0;r<rows;r++)
{
  for(c=0;c<columns;c++)
  {
 
   int liveNeighbourCount=getLiveNeighbours(r,c);
   int value=decideDeadorAlive(liveNeighbourCount,intArray[r][c]);

   printf("%d ",value);

  intArray[r][c]=value;
  }
printf("\n");
}

请告诉我我在这里做错了什么。

【问题讨论】:

  • intArray[i]=malloc(columns*sizeof(int*)); 应该是intArray[i]=malloc(columns*sizeof(int));,你想为你指向的东西分配空间。
  • 好的,但仍然没有修复错误。
  • 根据提供的代码,您似乎将未初始化的值 intArray[r][c] 传递给 decideDeadorAlive,请提供 minimal reproducible example
  • 您的函数确实会收到数组 [address]。你在使用 globals 吗?尝试在没有 globals 的情况下重写你的代码...globals are bad

标签: arrays c malloc


猜你喜欢
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2011-07-18
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多