c - 如何修复 ' Alrady print all array element of last row elements'

标签 c

总是数组的最后一行答案...

初始化变量...

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];

您创建了一个零乘零的数组。您稍后通过 scanfrowcolumn 赋值并不重要,因为那时您已经创建了 my_array。解决办法有两种:

<强>1。创建具有预定大小的数组。

仅此即可修复您的代码,因为用户永远不会输入超出缓冲区的值。 (如果您是 C 语言新手并且想理解我的意思,请尝试先将 rowcolumn 设置为 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/

相关文章:

c++ - QString 内部的 Qt QVarLengthArray

c - 如何使用带 pthreads 的线程池?

c - 如何在netfilter返回NF_DROP后停止后续数据包?

c - 数组声明方括号内的星号在C中是什么意思

c - 最大化 udp 性能

c - 递归函数 C?

c - Big-endian 或 Little-endian 对结构成员的影响是什么?

c - 试图理解 printf 中格式说明符的奇怪行为

iphone - 即时创建 *.docx(也许还有 *.doc?)文档?

c - 反转数组的函数 - C