Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program: Points with Structs Please help complete program below in C. The top of

ID: 3597181 • Letter: P

Question

Program: Points with Structs

Please help complete program below in C.

The top of a file contains a single number, say n. This number is then followed by n pairs of integer values representing points in the x-y plane. For example, 0 8 99-3 0 4 3 10 14 3 19 The name of the file comes into your program from the Unix command line in the form of argv1] Write a program first reads n and then reads in all n points I want you to read the x, y values into an array of structs. Space for the array of structs should be malloced up. Thus you will need to use a pointer to a struct. Do you see this? I want you to print out the points in the reverse order they were entered For example, the point 1 9 above will be the first output.

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>

struct coordinate {
int x;
int y;
};

int main(int argc, char *argv[])
{
FILE *fp = fopen(argv[1], "r");
int n;
fscanf(fp, "%d", &n);

struct coordinate *coordinates = (struct coordinate *)malloc(n*sizeof(struct coordinate*));

int i;
for(i = 0; i < n; i++) {
fscanf(fp, "%d%d", &(coordinates[i].x), &(coordinates[i].y));
}

for(i = n-1; i >= 0; i--) {
printf("%d %d ", coordinates[i].x, coordinates[i].y);
}

return 0;
}

sample run

cat file.txt

6
0 8
99 -3
0 4
-3 10
14 3
1 9

./a.out file.txt
1 9
14 3
-3 10
0 4
99 -3
0 8