C 维度矩阵中的访问冲突读取位置
我想得到你的帮助,了解并完成我的计划 这就是我要做的: “您必须练习以下程序: 首先,一个吸收的二维整数arr[M][N].M-行数N-列数。(矩阵大小从 (用户) 程序使用辅助功能“shift”移动数值矩阵的右一个位置,如图(2)所示 输入代替1,3代替2,4代替3,…20代替 第19名,第20名)。 Shift必须编写一个函数,并在示例矩阵循环中调用她三次……” 示例图片: 错误消息: 在尝试解决我放弃的问题后,我希望得到您的帮助,以了解我的代码中的错误。 是关于记忆吗? 这是我的代码:C 维度矩阵中的访问冲突读取位置,c,C,我想得到你的帮助,了解并完成我的计划 这就是我要做的: “您必须练习以下程序: 首先,一个吸收的二维整数arr[M][N].M-行数N-列数。(矩阵大小从 (用户) 程序使用辅助功能“shift”移动数值矩阵的右一个位置,如图(2)所示 输入代替1,3代替2,4代替3,…20代替 第19名,第20名)。 Shift必须编写一个函数,并在示例矩阵循环中调用她三次……” 示例图片: 错误消息: 在尝试解决我放弃的问题后,我希望得到您的帮助,以了解我的代码中的错误。 是关于记忆吗? 这是我的代
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "malloc.h"
void shift (int **arr,int rows,int cols);
void freemalloc ( int **arr,int rows);
void main()
{
int **arr,cols,rows;
int i,j;
printf("please insert rows and columns of the matrix: ");
scanf_s("%d%d",&rows,&cols);
arr=(int **)malloc(rows*sizeof(int *));
for(i=0; i<rows; i++)
arr[i]=(int *)malloc(cols*sizeof(int));
for (i=0; i<rows; i++)
for (j=0; j<cols; j++)
{
printf("rows %d , cols %d :\n", i, j);
scanf_s("%d", &arr[i][j]);
}
shift (arr,rows,cols);
freemalloc (arr,rows);
system("pause");
return ;
}
void shift (int **arr,int rows,int cols)
{
int i,j,temp=0;
for(i=0; i<rows ; i++ )
for( j=0 ; j<cols ; j++);
{
temp=arr[i][j];
arr[i][j]=arr[i][cols-1];
arr[i][cols-1]=temp;
}
for(i=0; i<rows ; i++)
{
for(j=0; j<cols ; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
void freemalloc ( int **arr,int rows)
{
int i;
for (i=0 ; i<rows ; i++)
{
free(arr[i]);
}
free(arr);
}
#包括“stdio.h”
#包括“conio.h”
#包括“stdlib.h”
#包括“malloc.h”
无效移位(整数**arr、整数行、整数列);
void freemalloc(整数**arr,整数行);
void main()
{
int**arr、cols、rows;
int i,j;
printf(“请插入矩阵的行和列:”);
扫描(“%d%d”行和列);
arr=(int**)malloc(rows*sizeof(int*);
对于(i=0;i我在一般评论中注意到了这一点,我将在这里对此进行放大。这是错误的,并且将导致未定义的行为:
for(i=0; i<rows ; i++ )
for( j=0 ; j<cols ; j++); // <<== this is wrong.
{
temp=arr[i][j];
arr[i][j]=arr[i][cols-1];
arr[i][cols-1]=temp;
}
通过删除分号来修复代码,至少解决了部分问题。我不能谈论其他问题
最后,将编译器警告设置为迂腐的级别。任何配置了适当增强警告的合理编译器都会发现这个问题。错误已经在另一个答案中指出,但让我给你另一条好建议:不要使用指向指针的指针来表示多维不规则数组。
另外,
这是你应该做的(应该做的):
如果包含标准头文件,如stdio.h
则改用
。此外,不应强制转换返回void*
的函数的返回值,如malloc
。至于您的问题,请在调试器中运行该程序,它将在崩溃位置停止,然后您可以检查函数调用堆栈d个局部变量和参数。在读取值时,您需要某种类型的分隔符,否则scanf将无法区分它们,您可能会使用未初始化的cols
value:scanf\us(“%d%d”、&rows,&cols);
您似乎在用C编写。您的标签上写着“C++”C和C++是非常不同的语言。我高度怀疑这一点:<代码>(j=0;j)。
// A useless nested for loop that runs `i` to `rows` and `j to `cols`
for(i=0; i<rows ; i++ )
for( j=0 ; j<cols ; j++);
// Now `i=rows` and `j=cols`. then you do this
temp=arr[i][j];
arr[i][j]=arr[i][cols-1];
arr[i][cols-1]=temp;
for(i=0; i<rows ; i++ )
for( j=0 ; j<cols ; j++) // note: no semi-colon.
{
temp=arr[i][j];
arr[i][j]=arr[i][cols-1];
arr[i][cols-1]=temp;
}
int (*mat)[width] = malloc(height * sizeof(*mat));