【问题标题】:2d arrays in c, unexpected value when the values are checkedc中的二维数组,检查值时出现意外值
【发布时间】:2014-12-12 18:40:57
【问题描述】:

这不是整个程序,只是其中的 sn-ps (据我所知)导致问题,如果需要更多,我会更新

我需要得到一个 0 的矩形数组来模拟网格

int Length, Height, NumberOfParticles, Direction, validInput, StartXPosition, StartYPosition;
int *LatticeHeight;
int **Lattice;

LatticeHeight = (int*)malloc(Height*sizeof(int));

/* 
    Check for memory allocation failure 
*/

if(LatticeHeight==NULL)
{
    printf("\nMemory allocation failure. Exiting ...\n");
    return(EXIT_FAILURE);
}

Lattice = (int**)malloc(Length*sizeof(LatticeHeight));

/* 
    Check for memory allocation failure again 
*/

if(Lattice==NULL)
{
    printf("\nMemory allocation failure. Exiting ...\n");
    return(EXIT_FAILURE);
}

然后有一些我遗漏的输入验证,但最终它会得到一个高度和长度的值

int i,j;
for(i=1; i<Height; i++)
{
    LatticeHeight[i] = 0;
}

for(j=0; j<Length; j++)
{
    Lattice[j] = LatticeHeight;
}

for(i=0;i<Height;i++)
{
    for(j=0;j<Length;j++)
    {
        printf("%d\n",Lattice[i][j]);
    }
}

这个打印语句返回

139064
0
0
0
139064
0
0
0
139064
0
0
0
139064
0
0
0

谁能解释一下原因?

【问题讨论】:

  • 你期望的输出是什么?
  • 16 个零,这是我在 Bhargav 指出我从 for 循环从 1 而不是 0 开始之后得到的

标签: c arrays pointers segmentation-fault


【解决方案1】:

你已经从1开始你的循环

for(i=1; i<Height; i++)
{
    LatticeHeight[i] = 0;
}

改成这个

for(i=0; i<Height; i++)
{
    LatticeHeight[i] = 0;
}

【讨论】:

  • @Aaron 小心,小心
猜你喜欢
  • 2017-02-10
  • 2013-08-15
  • 2012-11-08
  • 1970-01-01
  • 2014-02-13
  • 2011-06-26
  • 2018-01-20
  • 2020-01-24
  • 1970-01-01
相关资源
最近更新 更多