c - 在二维数组中使用指针运算

标签 c pointers multidimensional-array pointer-arithmetic

我需要使用指针算术来迭代二维数组并打印出插入到 main 中的坐标点。我似乎无法理解这一点...

`

#include <stdio.h>

void printTriangle(const int printPoints[3][2]);

int main()
{
    const int points[3][2];

    printf("Enter point #1 as x and y: ");
    scanf("%d %d", *(points + 0), *(points + 1));
    printf("Enter point #2 as x and y: ");
    scanf("%d %d", *(points + 2), *(points + 3));
    printf("Enter point #3 as x and y: ");
    scanf("%d %d", *(points + 4), *(points + 5));

    //printf("%d", points[2][0]);

    printf("\nStarting Triangle: ");
    printTriangle(points);
}

void printTriangle(const int printPoints[3][2])
{
    int *ptr;
    ptr = printPoints;

    int i = 0;
    int j = i + 1;

    for (i = 0; i<6;)
    {
        printf("(%d, %d)", *(ptr + i), *(ptr + i + 1));
        i += 2;
    }
}

最佳答案

您正在尝试更改数组,因此必须在不使用限定符 const 的情况下定义它。

对于指针算术,例如可以通过以下方式输入数组的值

int points[3][2];

printf("Enter point #1 as x and y: ");
scanf("%d %d", *points, *points + 1);
printf("Enter point #2 as x and y: ");
scanf("%d %d", *( points + 1), *( points + 1) + 1 );
printf("Enter point #3 as x and y: ");
scanf("%d %d", *( points + 2 ), *( points + 2 ) + 1 );

该函数还错误地使用了指针

void printTriangle(const int printPoints[3][2])
{
int *ptr;
ptr = printPoints;
^^^^^^^^^^^^^^^^^^
//...

函数的参数已调整为您尝试分配给 int * 类型的指针的 int ( * )[2] 类型。不存在从一种类型到另一种类型的隐式转换。

如果您想在函数内声明本地指针,则声明应如下所示

int ( *ptr )[2];
ptr = printPoints;
//...

关于c - 在二维数组中使用指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878167/

相关文章:

c++ - Windows进程管理

c - c中的指针和内存问题

c - node *node1 与 node* node1 有什么区别?

C指针数组/指针数组消歧

arrays - 有没有办法将 2D 数组传递到 pthreads 函数中?

c - 在进程之间异步传递文件描述符

C 将文件复制到结构中

多维动态数组中的 C++ 对象构造

c++ - 如何以相反的顺序访问数组中的元素?

c - 在 32 位或 64 位的一个字节中检测 ascii 字符