View Full Version : passing a struct through a function in C

11-05-2007, 08:52 PM
Small problem here, need ideas. i'm using a struct to read a text file of the format

Atomic Cluster
O -0.028882 -0.317470 0.526009
O 0.887822 0.327691 0.464289
O 0.956723 -0.765947 0.228034
O 0.419663 -0.075427 -0.474913

and then wanting to use the numerical data in a function that I have set up. Trouble is it's not actually passing the numerical values into my function and I'm not getting the desired output (Energy = -6.0 thereabout).

Question: Have i set up my struct correctly?
Question: Is this the correct way: energy(r[i].x,r[i].y,r[i].z);
to pass "substitute" the values in my loop into my function?
Question: Is my function prototype for energy set up correctly?

Many thanks for your help.

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

int N, i,j,k;
char A[50];
double Energy,Phi, phi;
float T,R;

char str[1];
float x;
float y;
float z;

void readcluster(void);
double energy(float a, float b, float c);

int main()
printf("Energy = %f\n", Phi);
printf("Energy per atom = %f\n", Energy);
return 0;

void readcluster(void)

double energy(float a, float b, float c);
FILE *fp = fopen("cluster.xyz", "r");
fscanf (fp,"%d\n", &N);
printf("\n%d\n", N);
while(!feof(fp)) {
if(fgets(A, 50, fp)) printf("%s", A);
i = 0;

while ((i <= N)&&(!feof(fp))){
fscanf (fp,"%s %f %f %f", &r[i].str[1], &r[i].x, &r[i].y, &r[i].z);
printf("O %f %f %f\n", r[i].x, r[i].y, r[i].z);



double energy(float a, float b, float c)
float XX, YY, ZZ;
for (j=i+1;j<=N;j++){
XX = pow(a - r[j].x,2.0);
YY = pow(b - r[j].y,2.0);
ZZ = pow(c - r[j].z,2.0);
R = sqrt(XX + YY + ZZ);
//printf("R[%d] = %f\n",j,R);
if(R < 0.890899){
phi = 8.0;
phi = 4*(pow(R,-12.0)-(pow(R,-6.0)));
Phi = Phi + phi;

Energy = Phi/N;
return 0;