在2D数组中使用指针算法

时间:2015-06-16 21:04:04

标签: c pointers multidimensional-array pointer-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;
    }
}

2 个答案:

答案 0 :(得分:1)

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

至于指针算术,那么例如可以按以下方式输入数组的值

button!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

该函数也错误地使用指针

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 *

答案 1 :(得分:0)

看起来你的问题实际上来自你的scanf陈述的结构。 scanf期望在格式字符串后给出一系列指针。但是,您可以使用*运算符取消引用指针。因此,scanf尝试分配存储在数组中的值所指向的地址,而不是数组中元素的地址。虽然您没有详细说明问题的确切性质。当我尝试分配时,我会得到段错误。如果删除*运算符,则应该能够通过指针运算进行赋值。

相关问题