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;
}
}
It looks like your problems are actually coming from the structure of your
scanfstatements.scanfexpects 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,scanftries 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.