c - 为什么我在使用双指针作为二维数组的参数时得到 'segmentation error'?

标签 c arrays pointers

问题是关于获取 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/

相关文章:

c - 如何修复类型参数与类型参数不兼容

java - 从java中字符串数组的ArrayList中选择不同的随机元素

c - 三个条件排列的最快算法是什么?

c - 在指向结构的指针中访问数组

php - 通知 : Array to string conversion with date

C:我如何使用 (.) 点运算符编写 ( x -> x-> x )

c# - C sharp "public IntPtr pHandle = IntPtr.Zero;"相当于 Delphi "hp: Pointer"

c - 通过将指针整数与 sizeof(int) 相乘来使用 realloc 不起作用

c - 用C语言中scanf的返回值做校验

arrays - Google Sheets - 查询具有不同结构的多个工作表