c - 请求用户输入二维数组并将数据存储在 C 数组中

标签 c arrays

我正在编写一个代码来帮助圣诞老人跟踪他在街道上需要的礼物数量,我正在尝试通过使用 2D 数组和嵌套 for 循环来实现这一点,显然这是正确的方法这样做,但在询问第二所房子里的 child 数量后,程序往往会崩溃。代码如下所示:

void distribute_presents()
{
   int houses, kids=0;
   int KidsInStreet[houses][kids];
   int i, j;
   printf("Enter the number of houses in the street?\n");
   scanf("%d", &houses);
   printf("Enter the number of kids in the street?\n");
   scanf("%d", &kids);
   for (i=0;i<=houses;i++)
   {
       for (j=0;j<=kids;j++)
       {
           printf("Enter the number of kids in house %d:\n", i+1, j+1);
           scanf("%d", KidsInStreet[i][j]);
       }
    }
     printf("The presents and their respective prices are:\n");
     for(i=0;i<=houses;i++)
    {
    for(j=0;j<=kids;j++)
    {
        printf("%d", KidsInStreet[i][j]);
    }
}
}

最佳答案

我认为您应该首先查询房屋和 child 的数量,然后填充二维数组:

void distribute_presents()
{
    int houses, kids = 0;
    int i, j;
    printf("Enter the number of houses in the street?\n");
    scanf("%d", &houses);
    printf("Enter the number of kids in the street?\n");
    scanf("%d", &kids);
    int KidsInStreet[houses][kids];

    for (i=0; i < houses; i++)
    {
        for (j=0; j < kids; j++)
        {
            printf("Enter the number of kids in house %d:\n", i+1);
            scanf("%d", &KidsInStreet[i][j]);
        }
    }
    printf("The presents and their respective prices are:\n");
    for (i=0; i < houses; i++)
    {
        for (j=0; j < kids; j++)
        {
            printf("%d", &KidsInStreet[i][j]);
        }
    }
}

关于c - 请求用户输入二维数组并将数据存储在 C 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049598/

相关文章:

c - 将指针(字符串)深入传递给函数的方式

c - 在 MacOSX 上使用 OpenCV 2.4.13.2 上的 C API 创建并保存视频后无法打开视频

c - 生成与一组 vector 线性无关的随机 vector

arrays - 在 Matlab 中存储固定大小和数据类型的多个图像的所有可能且内存有效的方法是什么?

python - 堆叠稀疏和密集矩阵

javascript - 如何从 firebase-database 数据列表返回一个数组

c++ - 目前在 Ubuntu C/C++ 中如何将 IANA 时区名称转换为 UTC 偏移量

arrays - 需要帮助根据文件名中的时间戳对文件列表进行排序

javascript - JavaScript tic tac toe 游戏中的错误

c - MIL-STD-1750A 到十进制转换示例