centroid.c, 2020-09-24, section 1

/* point explorer
| 2020-09-24
*/
#include <stdio.h>
#include <stdlib.h>     // malloc()
#include <string.h>     // strlen()
#include <math.h>

struct Point {
    double x, y, z;
    char *name;
} ;

struct Point centroid(struct Point *obj, int n)
{
    double x = 0.0, y = 0.0, z = 0.0;
    for (int p = 0; p < n; p++) {
        x += obj[p].x;
        y += obj[p].y;
        z += obj[p].z;
    }
    struct Point c;
    c.x = x / (double)n;
    c.y = y / (double)n;
    c.z = z / (double)n;
    int nlen = strlen(obj[0].name) + 1;
    c.name = malloc(nlen * sizeof(char));
    strncpy(c.name, obj[0].name, nlen);

    printf("returning point at %p\n", &c);
    return c;
}

int main(int argc, char **argv)
{
    FILE *handle;
    
    if (argc < 2) {
        printf("no filename!\n");
        return 1;
    }
    handle = fopen(argv[1], "r");

    int npoints;
    fscanf(handle, " %d", &npoints);    // object's size
    char buffer[2048];
    fgets(buffer, 2048, handle);            // object's name

    struct Point myobject[ npoints ];
    for (int p = 0; p < npoints; p++) {
        fscanf(handle, " %lf %lf %lf", 
            &(myobject[p].x),
            &(myobject[p].y),
            &(myobject[p].z)
        );
        int namelen = strlen(buffer) + 1;
        myobject[p].name = malloc(namelen * sizeof(char));
        strncpy( myobject[p].name, buffer, namelen);
    } 

    struct Point objcentroid = centroid(myobject, npoints);

    for (int p = 0; p < npoints; p++) {
        printf("point %2d:  %.3lf,  %.3lf,  %.3lf\n", p, myobject[p].x, myobject[p].y, myobject[p].z);
    }

    printf("Centroid of %s, at address %p:  (%lf, %lf, %lf)\n", objcentroid.name, &objcentroid,
        objcentroid.x, objcentroid.y, objcentroid.z);

    return 0;
}