Hello,
i'm still trying to learn C, and I have a new question ;).
I want to declare a struct, and use a function to manipulate the entries. If I change the values within a function it's ok; however, when i access the members outside the function, they're not defined anymore.
How do i change the values in the struct such that a different function can use it as well? I thought using a pointer to struct would be 'good enough', but apparently it isn't ;).
Thanks in advance,
#include <stdio.h>
#include <stdlib.h> // for drand48
#include <math.h>
struct atom{
double x,y,z;
double vx,vy,vz;
double fx,fy,fz;
int id;
};
void initialpos(struct atom *name, int N);
const int N=100;
int main()
{
struct atom *patom[100];
int i;
for (i = 0; i < N; i++)
{
patom[i]=(struct atom *)malloc(sizeof(struct atom));
}
for (i = 0; i < N; i++)
{
if (patom[i]==NULL)
{
printf("out of MEM\n");
return 1;
}
}
/* give atoms their initial position */
initialpos(patom[0],N);
for (i = 0; i < N; i++)
{
printf("pos. of %d: %f\t %f\t %f\t \n", i, patom[i]->x, patom[i]->y, patom[i]->z);
}
return 0;
}
void initialpos(struct atom *name, int N)
{
int i;
for (i = 0; i < N; i++)
{
name[i].x=drand48()*20;
name[i].y=drand48()*20;
name[i].z=drand48()*20;
printf("pos of %d: %f\t %f\t %f\t \n", i, name[i].x, name[i].y, name[i].z);
}
}