【问题标题】:Using Pointer Arithmetic in a 2D Array在二维数组中使用指针算术
【发布时间】:2015-06-16 21:04:03
【问题描述】:

我需要使用指针 Arithmetic 来遍历一个 2D 数组并打印出插入 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;
    }
}

【问题讨论】:

  • 究竟是什么不工作?编译错误?输出错误?发布错误或至少预期的结果。
  • 使用 &amp;points[2][0] 代替 *(points + 4) ,依此类推。它们不是一回事。

标签: c pointers multidimensional-array pointer-arithmetic


【解决方案1】:

您正在尝试更改数组,因此必须在没有限定符 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 ( * )[2] 类型,您试图将其分配给int * 类型的指针。没有从一种类型到另一种类型的隐式转换。

如果你想在函数中声明一个局部指针,那么声明应该是这样的

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

【讨论】:

    【解决方案2】:

    看起来您的问题实际上来自您的 scanf 语句的结构。 scanf 期望在格式字符串之后给出一系列指针。但是,您正在使用 * 运算符取消引用指针。因此,scanf 尝试分配给存储在数组中的值所指向的地址,而不是数组中元素的地址。尽管您没有指定问题的确切性质。当我尝试按照您所做的分配时,我会遇到段错误。如果您删除 * 运算符,您应该能够通过指针算法进行分配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      相关资源
      最近更新 更多