error in dynamic memory using struct

hi all, i'm trying to make a array dynamically using new
the struct and the code that call the struct aren given here:

1
2
3
4
5
struct Vector3 {
    double x;
    double y;
    double z;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//the prerequisites are not display here 
Vector3* xt     = new Vector3 [nx * ny * nz];
Vector3* vort   = new Vector3 [nx * ny * nz];

for(unsigned int i = 0; i < nx; ++i) {
    for(unsigned int j = 0; j < ny; ++j) {
        for(unsigned int k = 0; k < nz; ++k) {

            double bheta_core;
            double r2;
            double vtt;

            unsigned int it  = k + ny * (j + nx * i);

            xt[it].x = xmin.x + (i + 0.5e0) * ht;
            xt[it].y = xmin.y + (j + 0.5e0) * ht;
            xt[it].z = xmin.z + (k + 0.5e0) * ht;

            bheta_core  = atan2( xt[it].y - xcen.y, xt[it].x - xcen.x );
            r2          = sqrt( (xt[it].x - xcen.x) * (xt[it].x - xcen.x) +
                                (xt[it].y - xcen.y) * (xt[it].y - xcen.y) );
            r2         -= r_ring;
            r2         *= r2;
            r2         += ( xt[it].z - xcen.z ) * ( xt[it].z - xcen.z );

            vtt         = vort_max * exp(-r2 / (2.0e0 * sig_ring2));
            vort[it].x  = -vtt * sin(bheta_core);
            vort[it].y  =  vtt * cos(bheta_core);
            vort[it].z  =  0.0e0;

        //== end of for: start
        };
    };
};
delete [] xt;
delete [] vort;


the problem is when i tried to run using g++ 4.4.3, it gave me error msg:
Segmentation fault

thus i tried to compile using my xcode 4.3, it gave me error msg:
Thread 1: EXC_BAD_ACCESS(code=1, address=0x108c36000)


anyone can help me about this?
At the first look, i think i would have writen something like
unsigned int it = k*(ny*nx)+j*nx+i;
yes i tried ur suggestion bartoli, it works well now. i worder why.. could you explained to me?
Last edited on
I suppose your calculation of it was wrong and gave positions bigger thant the size of the array for some values of nx/ny/nz ,or wrong positions when it was not overflowing.

Take a size of 10 in each dimension for example.
The last it calculated (for nx=ny=nz=9) would be
9+9*(9+9*9) = 9+9*90 = 819, when i think you would want 999
thank.. it was a silly mistake, i didnt calculate it right
Topic archived. No new replies allowed.