Using Pointer Arithmetic in a 2D Array

225 views Asked by At

I need to use pointer Arithmetic to iterate through a 2D array and print out the coordinate points inserted in main. I can't seem to get this right...

`

#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

There are 2 answers

0
Vlad from Moscow On

You are trying to change the array so it must be defined without the qualifier const.

As for the pointer arithmetic then for example the values of the array can be entered the following way

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 );

The function also uses pointers incorrectly

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

The parameter of the function is adjusted to type int ( * )[2] that you are trying to assign to a pointer of type int *. There is no implicit conversion from the one type to another.

If you want to declare a local pointer within the function then the declaration should look like

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

It looks like your problems are actually coming from the structure of your scanf statements. scanf expects a to be given a series of pointers to be given after the format string. You are, however, dereferencing the pointers by using the * operator. Thus, scanf tries to assign to the addresses pointed to by the values stored in your array, rather than the addresses of the elements in your array. Although you don't specify the exact nature of your problems. I get segfaults when I try to assign as you have done. If you remove the * operators, you should be able to make the assignments through pointer arithmetic.