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

/* object 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 calc_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;
    c.name = obj[0].name;
    
    return c;
}


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

    int npoints;
    fscanf(handle, " %d", &npoints);
    char buffer[4096];
    //fscanf(handle, " %s", buffer);
    fgets(buffer, 4096, handle);

    int nlen = strlen(buffer) + 1;
    char *mypoint = malloc( nlen * sizeof(char) );
    strncpy(mypoint, buffer, nlen);

    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)
        );
        myobject[p].name = mypoint;
    }

    struct Point centroid = calc_centroid(myobject, npoints);

    printf("centroid of object %s:  (%lf, %lf, %lf)\n",
        centroid.name, centroid.x, centroid.y, centroid.z);

    return 0;
}