【问题标题】:How to properly insert data in 2D array in C?如何在 C 中正确插入二维数组中的数据?
【发布时间】:2021-09-10 00:15:12
【问题描述】:

这里我有 3 个二维数组,arrayActivearrayDeatharrayRecovery。我正在尝试使用 for 循环将数据插入到我的每个数组中。然后我试图用arrayActive 减去其他2个数组。但是我得到的输出不正确。

这些是 3 个数组:

int arrayActive[4][1];

    for(int i=0; i<5; i++)
    {
        for(int y=0; y<1; y++)
        {
            printf("Enter the number of active cases in the state %d are : ",i+1);
            scanf("%d",  &arrayActive[i][y]);
        }
    }


    int arrayDeath[4][1];
    for(int i=0; i<5; i++ )
    {
        for(int y=0; y<1; y++)
        {
            printf("Enter the number of Death cases in the state %d are : ",y+1);
            scanf("%d",  &arrayDeath[i][y]);
        }
    }


    int arrayRecover[4][1];
    for(int i=0; i<5; i++)
    {
        for(int y=0; y<1; y++)
        {
            printf("Enter the number of recovery cases in the state %d are : ",i+1);
            scanf("%d",&arrayRecover[i][y]);

        }
    }

在这里我试图得到不正确的减法后的所有输出:

 int activeCasesStateWise[4];
    for(int i=0; i<5; i++)
    {
for(int y=0; y<1; y++)
{

    activeCasesStateWise[i]= arrayActive[i][y]-arrayRecover[i][y] - arrayDeath[i][y];

    printf("Here array active case %d and recover case %d and death cases %d the So  cumulative active cases for state 1 are %d \n", arrayActive[i][y],arrayRecover[i][y],arrayDeath[i][y],activeCasesStateWise[i]);
}

【问题讨论】:

  • int arrayActive[4][1]; for(int i=0; i&lt;5; i++) 定义大小为 4 的数组时,有效索引为 0-3。您在此处的循环将从 i = 0 到 4 执行,在最后一次迭代中调用未定义的行为。您应该将大小从 4 增加到 5,或者在循环条件中将 5 更改为 4。
  • 为什么你有一个二维数组,其中第二维的大小为 1?这是某种 API 原因吗?

标签: arrays c for-loop


【解决方案1】:

您已经声明了一个包含 4 行的数组,并且在 for 循环中,您也在为第 5 行添加值。因此,您的程序无法运行并崩溃。 您将必须更改所有外部循环的条件,如下所示: for(int i=0; i; i++)

【讨论】:

    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 2015-05-10
    • 2020-11-08
    • 2013-11-30
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多