总是数组的最后一行答案...
初始化变量...
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];
您创建了一个零乘零的数组。您稍后通过 scanf
为 row
和 column
赋值并不重要,因为那时您已经创建了 my_array
。解决办法有两种:
<强>1。创建具有预定大小的数组。
仅此即可修复您的代码,因为用户永远不会输入超出缓冲区的值。 (如果您是 C 语言新手并且想理解我的意思,请尝试先将 row
和 column
设置为 25。您的程序将可以运行。但是然后看看当您尝试遍历 25 x 25 数组时会发生什么。哦,不,代码再次中断!)。
<强>2。使用malloc
动态分配内存。
像这样声明一个二维数组:
int **my_array;
一旦获得row
,就malloc(sizeof(int *) * row);
,然后循环遍历my_array
,分配列。如果这一切对你来说完全陌生,我建议你看看 Beej's Guide to C Programming关于指针的部分。祝你好运!
关于c - 如何修复 ' Alrady print all array element of last row elements',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54049369/