Laxmi
Laxmi

Reputation: 91

How to modify this function to use structs as arguments rather than doubles

/* the struct */
typedef struct atom {
    double x;
    double y;
    double z;
    char line[200];
    int is_connected;
    struct atom *next;
} p_atom;

/* the existing function */  
double
calcdist (double px, double py, double pz, double lx, double ly, double lz )   
{  
    double x, y, z, sqr_sum;
    x = px - lx;
    y = py - ly;
    z = pz - lz;
    sqr_sum = pow (x, 2) + pow (y, 2) + pow (z, 2);
    return sqrt (sqr_sum);
}
  1. The above program is written to calculate distance between 2 points in 3D. If I want to write a new function that accepts x,y,z coordinates via my struct and calculates distance (same as above), is it possible...if so how?
  2. How do I execute a c program giving multiple input files on the command line.

Upvotes: 0

Views: 72

Answers (3)

milevyo
milevyo

Reputation: 2184

the elegant:

typedef struct {
    double          x;
    double          y;
    double          z;
}COORD_3D;



typedef struct atom {
    COORD_3D        coord;
    char            line[200];
    int             is_connected;
    struct atom     *next;
} p_atom;



double calc3Ddist (COORD_3D *coord1, COORD_3D *coord2)   
{  
    double x, y, z, sqr_sum;
    x = coord1->x - coord2->x;
    y = coord1->y - coord2->y;
    z = coord1->z - coord2->z;

    sqr_sum = pow (x, 2) + pow (y, 2) + pow (z, 2);
    return sqrt (sqr_sum);
}


int HowToDo(){

    p_atom      a, b;
    int         dist;

    dist=calcdist( &a.coord, &b.coord);

}

Upvotes: 0

milevyo
milevyo

Reputation: 2184

the simpler:

double
calcdist (p_atom *patom, p_atom *latom )   
{  
    double x, y, z, sqr_sum;
    x = patom->x - latom->x;
    y = patom->y - latom->y;
    z = patom->z - latom->z;

    sqr_sum = pow (x, 2) + pow (y, 2) + pow (z, 2);
    return sqrt (sqr_sum);
}

Upvotes: -1

tdao
tdao

Reputation: 17713

Perhaps the first thing to do is to read a C book, especially on how a function works.. I'll give you some hints anyway.

  1. If i want to write a subroutine that accepts x,y,z coordinates and calculates distance (same as above), is it possible...if so how?

It is possible, and actually the good way to do it. You can pass as many parameters to function as you want. In this case, however, it's probably better to pass pointer to struct. That way is usually more convenient and more efficient than passing several parameters.

double calcdist( p_atom *point1, p_atom *point2 )

Inside that function, you can do the calculation with point1->x, point1->y, etc. as you currently do with your px, py, etc.

  1. How to execute a c program by giving multiple input files in command line

You can cat multiple input files and then pipe them to your program. Something like:

cat file1 file2 | ./a.out

Upvotes: 3

Related Questions