I want to implement a simple N-body simulation and to manage all the pairwise interactions I wanted to use a linked list to compute only interactions between neighbours. This is the code:
#include <stdio.h>
#include <stdlib.h>
#define V 20
#define N_P 100
typedef struct _node{
int id;
struct _node *next;
} node;
typedef struct _particle{
double r[3];
node* n;
int coor[3];
} particle;
typedef struct _simulation_struct{
int N;
particle *system;
double L[3];
double s[3];
int nc[3];
node*** cell;
} simulation_struct;
simulation_struct *new_simulation(int N, double Lx, double Ly,double Lz,double R);
int main()
{
simulation_struct *simulation=new_simulation(N_P,V,V,V,2);
return 0;
}
simulation_struct *new_simulation(int N, double Lx, double Ly, double Lz,double R)
{
simulation_struct *simulation;
int i, j,k;
simulation =(simulation_struct*) malloc(1*sizeof(simulation));
simulation->N = N;
simulation->L[0] = Lx;
simulation->L[1] = Ly;
simulation->L[2] = Lz;
simulation->nc[0] = (int) (Lx/R)+1;
simulation->nc[1] = (int) (Lx/R)+1;
simulation->nc[2] = (int) (Lx/R)+1;
simulation->s[0] = Lx/simulation->nc[0];
simulation->s[1] = Ly/simulation->nc[1];
simulation->s[2] = Lz/simulation->nc[2];
simulation->system = (particle*)malloc(N*sizeof(particle));
simulation->cell =(node***) malloc ((simulation->nc[0])*sizeof(node **));
for (i=0; i < simulation->nc[0]; i++)
{
simulation->cell[i] = (node**)malloc((simulation >nc[1])*sizeof(node*));
for (j=0; j < simulation->nc[1];j++)
{
simulation->cell[i][j] = (node*)malloc((simulation->nc[2])*sizeof(node));
for (k=0; k < simulation->nc[2];k++)
{
simulation->cell[i][j][k].id = -1;
simulation->cell[i][j][k].next = NULL;
}
}
}
for (i=0; i < simulation->nc[0]; i++)
{
simulation->system[i].n = (node*)malloc(1*sizeof(node));
simulation->system[i].n->id = i;
}
return simulation;
}
I can compile it, and if the parameters V and N_P are small (e.g. V=10 N_P=20) the programs works fine, but if the parameters are a little bit bigger when I execute the program I find a segmentation fault error.Could someone tell me what I'm doing wrong?
Thanks in advance!!!!