c - 如何修复'Alrady打印最后一行元素的所有数组元素'
问题描述
总是来数组的最后一行答案......
初始化变量...
int row,column;
row=0;
column=0;
int i,j;
i=0,j=0;
int my_array[row][column];
int sum=0;
用户可以输入数组值...
printf("enter row values & column value:\n ");
printf("row value i :");
scanf("%d",&i);
printf("column value :");
scanf("%d",&j);
printf("Set the values...\n");
printf("\n");
获取数组到值...
for(row=0;row<=i-1;row++)
{
for(column=0;column<=j-1;column++)
{
printf("Enter value for my_array[%d][%d] :",row,column);
scanf("%d",&my_array[row][column]);
}
}
打印数组....
for(row=0;row<=i-1;row++)
{
for(column=0;column<=j-1;column++)
{
printf("%d ",my_array[row][column]);
}
printf("\n");
}
//end of the code
return 0;
解决方案
这是你的问题,
int row,column;
row=0;
column=0;
// ...
int my_array[row][column];
您创建一个零乘零数组。row
稍后将值分配给和column
via并不重要,scanf
因为那时您已经创建了my_array
. 有两种解决方案:
1. 创建预定大小的数组。
仅此一项就可以单独修复您的代码,因为用户从不输入超出缓冲区的值。(如果您是 C 新手并且想理解我的意思,请尝试尝试设置row
并column
从 25 开始。您的程序会工作。但是然后看看当您尝试超过25 x 25 数组时会发生什么。哦不,代码再次中断!)。
2. 使用动态分配内存malloc
。
像这样声明一个二维数组:
int **my_array;
一旦你得到row
, you malloc(sizeof(int *) * row);
,然后你遍历my_array
,分配列。如果这一切对您来说完全陌生,我建议您查看Beej 的 C 编程指南关于指针的部分。祝你好运!
推荐阅读
- python - 使用 oauth2 的烧瓶登录会话不起作用
- electron-builder - 无法下载应用程序
- sql-server - 加速将数据从 SQL Server 引用/导入 Excel 的代码
- python - 如何在 Python 中将 JSON 字符串值转换为小写?
- laravel - 如何正确设置 PhpStorm?Сan't run PHPUnit on Laravel 8 on Windows 10. 调用未定义函数 Tests\Unit\is_id_term()
- c++ - 如何加快程序执行速度?
- javascript - Vue 3 Composition API,使用 valueAsDate 属性设置日期输入
- sql - SQL试图分隔数据库字段中的条目值
- multithreading - Nasm - 在不同的线程中更改变量
- python - 你如何在 python tkinter 中组合两个窗口?刽子手计划