首页 > 解决方案 > 如何修复'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;

标签: c

解决方案


这是你的问题,

int row,column;
row=0;
column=0;
// ...
int my_array[row][column];

您创建一个零乘零数组。row稍后将值分配给和columnvia并不重要,scanf因为那时您已经创建了my_array. 有两种解决方案:

1. 创建预定大小的数组。

仅此一项就可以单独修复您的代码,因为用户从不输入超出缓冲区的值。(如果您是 C 新手并且想理解我的意思,请尝试尝试设置rowcolumn从 25 开始。您的程序会工作。但是然后看看当您尝试超过25 x 25 数组时会发生什么。哦不,代码再次中断!)。

2. 使用动态分配内存malloc

像这样声明一个二维数组:

int **my_array;

一旦你得到row, you malloc(sizeof(int *) * row);,然后你遍历my_array,分配列。如果这一切对您来说完全陌生,我建议您查看Beej 的 C 编程指南关于指针的部分。祝你好运!


推荐阅读