Ficheiros pontos.c
:
#include <stdio.h> #include <stdlib.h> typedef struct { int x; int y; } Ponto; typedef struct { Ponto se; Ponto id; } Rectangulo; Ponto * lePontos(int n); void escrevePontos(Ponto * pontos, int n); Rectangulo * defineRectangulo(Ponto * pontos, int n); int main() { Ponto *v; Rectangulo *r; int n; scanf("%d", &n); v = lePontos(n); escrevePontos(v, n); r = defineRectangulo(v, n); printf("SE x:%d y:%d\n", r->se.x, r->se.y); printf("ID x:%d y:%d\n", r->id.x, r->id.y); free(v); free(r); return EXIT_SUCCESS; } Ponto * lePontos(int n) { int i; Ponto *v = malloc(sizeof(Ponto) * n); for (i = 0; i < n; i++) scanf("%d%d", &v[i].x, &v[i].y); return v; } void escrevePontos(Ponto * pontos, int n) { int i; for (i = 0; i < n; i++) printf("x:%d y:%d\n", pontos[i].x, pontos[i].y); } Rectangulo * defineRectangulo(Ponto * v, int n) { int i; Rectangulo * r = malloc(sizeof(Rectangulo)); r->se.x = r->id.x = v[0].x; r->se.y = r->id.y = v[0].y; for (i = 1; i < n; i++) { if (v[i].x < r->se.x) r->se.x = v[i].x; if (v[i].x > r->id.x) r->id.x = v[i].x; if (v[i].y > r->se.y) r->se.y = v[i].y; if (v[i].y < r->id.y) r->id.y = v[i].y; } return r; }
Compilar e executar:
[aplf@darkstar ~]$ gcc -g -Wall -ansi -pedantic -o pontos pontos.c [aplf@darkstar ~]$ valgrind ./pontos ==6125== Memcheck, a memory error detector ==6125== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==6125== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info ==6125== Command: ./pontos ==6125== 3 1 2 1 4 2 3 x:1 y:2 x:1 y:4 x:2 y:3 SE x:1 y:4 ID x:2 y:2 ==6125== ==6125== HEAP SUMMARY: ==6125== in use at exit: 0 bytes in 0 blocks ==6125== total heap usage: 2 allocs, 2 frees, 40 bytes allocated ==6125== ==6125== All heap blocks were freed -- no leaks are possible ==6125== ==6125== For counts of detected and suppressed errors, rerun with: -v ==6125== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2) [aplf@darkstar ~]$