我需要使用指针算术来迭代二维数组并打印出插入到 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/