问题是关于获取 4X5 矩阵的输入并将其每一行向左循环移动 2 位。就像如果输入是 {1,2,3,4,5} 输出应该是 {3,4,5,1,2}。我为此编写了以下代码。但我收到“段错误(核心转储)”错误。你能帮我解决这个问题吗?此外,我对发送二维数组以使用 **p 参数起作用有点敏感。也请对此发表评论。我想知道为什么会出现错误。
#include <stdio.h>
void shift(int **);
int main()
{
int i,j,a[4][5];
printf("Enter the elements of the 4X5 matrix:\n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Entered Matrix:\n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("\n");
shift(a);
printf("The new array is:\n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}
void shift(int **p)
{
int i;
for(i=0;i<4;i++)
{
int temp[2] = {**(p+i),*(*(p+i)+1)};
*(*(p+i)+0) = *(*(p+i)+2);
*(*(p+i)+1) = *(*(p+i)+3);
*(*(p+i)+2) = *(*(p+i)+4);
*(*(p+i)+3) = temp[0];
*(*(p+i)+4) = temp[1];
}
}
预期结果 - 旋转数组 实际结果——Segmentation Fault(Core Dumped)
最佳答案
像这样访问二维数组的数组元素只适用于二维数组。而不是这样声明:
void shift(int **p)
你应该把它改成这样:
void shift(int p[4][5])
函数的原型(prototype)也是如此。 Click here用于演示。
关于c - 为什么我在使用双指针作为二维数组的参数时得到 'segmentation error'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460262/