C++ code function not writing data of multidimensional array to file in function (using VS2015 windows 8)

Hello fellow C++ programmers I have created some code for light photon travel but I feel some somehow array indexing relating to a pointer is not function correctly. This code is at the end of my program.. when debugging I get this error:

Exception thrown at 0x00887EB2 in MonteCarloDemo.exe: 0xC0000005: Access violation reading location 0x80000008.
If there is a handler for this exception, the program may be safely continued.

This error is around a multidimensional array related to flux F[100][100]..see below.The function(declaration) involved is:
1
2
3
4
void SaveFile(int Nfile, double *J,double**F, double specularreflec, double absorbingFrac, double escapingFrac,
		double absorbCoeff, double scattCoeff, double anisG, double n1, double n2,
		int mcflag, double radius, double waist, double xs, double ys, double zs,
		int NR, int NZ, double dr, double dz, const int Nphotons);


Function body is:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
void Photon::SaveFile(int Nfile, double *J,double **F, double specularreflec, double absorbingFrac, double escapingFrac,
	double absorbCoeff, double scattCoeff, double anisG, double n1, double n2,
	int mcflag, double radius, double waist, double xs, double ys, double zs,
	int NR, int NZ, double dr, double dz, const int Nphotons)
{
	double	r, z, r1, r2;
	long ir, iz;
	std::string filename = "";
	/*
	do {
	getline(cin, measuremntOp);
	} while (measuremntOp != "MAX" && measuremntOp != "MIN" && measuremntOp != "AVERAGE");
	*/
	std::ofstream targetFile;
	cout << "Type in the name of the file you will use to store data from simulation above:";
	do {
		getline(cin, filename);
	} while (filename =="");
	
	targetFile.open(filename, std::ios::out);

	targetFile << "absorbtion coefficient[1/cm] " << absorbCoeff << "\n";
	//fprintf(target, "%0.4f\tmus, scattering coefficient [1/cm]\n", mus);
	cout << "scattering coefficient[1/cm] " << scattCoeff << "\n";
	//fprintf(target, "%0.4f\tg, anisotropy [-]\n", g);
	targetFile << "anisotropy[-] " << anisG << "\n";
	//fprintf(target, "%0.4f\tn1, refractive index of tissue\n", n1);
	targetFile << "refractive index of tissue" << n1 << "\n";
	//fprintf(target, "%0.4f\tn2, refractive index of outside medium\n", n2);
	targetFile << "refractive index outside of tissue " << n2 << "\n";
	//fprintf(target, "%d\tmcflag\n", mcflag);
	targetFile << "tmcflag: " << mcflag << "\n";
	//fprintf(target, "%0.4f\tradius, radius of flat beam or 1/e radius of Gaussian beam [cm]\n", radius);
	targetFile << "radius of flat beam or 1/e radius of Gaussian beam [cm]:" << radius << "\n";
	//fprintf(target, "%0.4f\twaist, 1/e waist of focus [cm]\n", waist);
	targetFile << "radius of flat beam or 1 / e radius of Gaussian beam[cm]:" << waist << "\n";
	targetFile << "x position of isotropic source [cm]\n " << xs << " \n";
	targetFile << "ys, y:" << ys << "\n";
	targetFile << "tzs, z:" << zs << "\n";
	targetFile << "NR:" << NR << "\n";
	targetFile << "NZ:" << NR << "\n";
	targetFile << "dr:" << dr << "\n";
	targetFile << "dz:" << dr << "\n";
	targetFile << "Number of photons launched:" << Nphotons << "\n";

	/* print SAE values */
	targetFile << "Specular reflectance:" << specularreflec << "\n",
		targetFile << "Absorbed fraction:" << absorbingFrac << "\n";
	targetFile << "Escaping fraction:" << escapingFrac << "\n";

	/* print r[ir] to row */
	targetFile << 0.0; /* ignore upperleft element of matrix */
	for (ir = 1; ir <= NR; ir++) {
		r2 = dr*ir;
		r1 = dr*(ir - 1);
		r = 2.0 / 3 * (r2*r2 + r2*r1 + r1*r1) / (r1 + r2);
		targetFile << r;
	}
	targetFile << "\n";

	/* print J[ir] to next row */
	targetFile << 0.0; /* ignore this 1st element of 2nd row */
	for (ir = 1; ir <= NR; ir++) {
		targetFile << J[ir];
	}
	targetFile << "\n";

	/* printf z[iz], F[iz][ir] to remaining rows */
	for (iz = 1; iz <=NZ; iz++) {
		z = (iz - 0.5)*dz; /* z values for depth position in 1st column */
		targetFile << z;
		for (ir = 1; ir <=NR; ir++){
			targetFile << F[iz][ir] << "\n";
		//targetFile << "\n";
	     }
	}
	targetFile.close();
} 



The error during debugging is thrown on line targetFile <<F[iz][ir] <<"\n"; near the end. Everything before that works fine and is written to the file as usual.Can someone tell me what I am doing wrong here regarding F which is a multidimensional array collection light photon flux


I will add some code below that is before this last function above and is in the main method:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
   ir = (long)(r2 / dr) + 1; /* round to 1 <= ir */
        iz = (long)(fabs(z) / dz) + 1;  /* round to 1 <= iz */
        if (ir >= NR) ir = NR; /* last bin is for overflow */
	if (iz >= NZ) iz = NZ;  /* last bin is for overflow */
     F[iz][ir] += absorb;  /* DROP absorbed weight into bin */
     /**** SPIN
     * Scatter photon into new trajectory defined by theta and psi.
     * Theta is specified by cos(theta), which is determined
      * based on the Henyey-Greenstein scattering function
       * Convert theta and psi into cosines ux, uy, uz
      *****/
     /* Sample for costheta */
	if (skinAnis == 0.0)
	costheta = 2.0*rnd - 1.0;
	     else if (skinAnis == 1.0)
	costheta = 1.0;
	else {
	temp = (1.0 - skinAnis*skinAnis) / (1.0 - skinAnis + 2 * skinAnis*rnd);
	costheta = (1.0 + skinAnis*skinAnis - temp*temp) / (2.0*skinAnis);
	     }
	sintheta = sqrt(1.0 - costheta*costheta);/*sqrt faster than sin()*/
       /* Sample psi. */
	psi = 2.0*PI*printRandomDouble(0.0, 1.01);
	cospsi = cos(psi);
	if (psi < PI)
       sinpsi = sqrt(1.0 - cospsi*cospsi); /*sqrt faster */
	else
	sinpsi = -sqrt(1.0 - cospsi*cospsi);
       /* New trajectory. */
	if (1 - fabs(uz) <= 1.0e-12) {  /* close to perpendicular. */
		uxx = sintheta*cospsi;
		uyy = sintheta*sinpsi;
		uzz = costheta*((uz) >= 0 ? 1 : -1);
	}
	else {   /* usually use this option */
		temp = sqrt(1.0 - uz*uz);
	uxx = sintheta*(ux*uz*cospsi - uy*sinpsi) / temp + ux*costheta;
	uyy = sintheta*(uy*uz*cospsi + ux*sinpsi) / temp + uy*costheta;
	uzz = -sintheta*cospsi*temp + uz*costheta;
		}
       /* Update trajectory */
		ux = uxx;
		uy = uyy;
		uz = uzz;

	}
	if (rouletteChoice == 1) {
		if (photon_weight < THRESHOLD) {
		if (rnd <= CHANCE)
		photon_weight /= CHANCE;
		else photon_condition = DEAD;
			}
		}
     else { //if person chose roulette option 2
	int indexSelector1 = printRandomInt(0, monowaveNum);
	double percentkeLoss1 = (energyLeft[indexSelector1] / photonE[indexSelector1])*100.0;
	if (percentkeLoss1 > 65.0) {
	photon_condition = DEAD;
	}
      else {
	if(randomNum > PROB_SURVIVAL) {
	photon_condition = DEAD;
	}
       else {
	photon_weight = photon_weight / PROB_SURVIVAL;
	    }
	}

	}//rouletteChoice 2
        } while (photon_condition == ALIVE);
	int a = 0;
	rhoSpherVals[a] = distsofarSph;
	rhoCylinVals[a] = distsofarCyl;
	rhoPlanarVals[a] = distsofarPla;
       rhoCounter += 1;
	xVal[a] = x;
       yVal[a] = y;
	zVal[a] = z;
	xPlaneDir[a] = ux;
	yPlaneDir[a] = uy;
	zPlaneDir[a] = uz;
	++a;
	current_Phot += 1;
	p1.totalDistTravelled(distsofarSph, "continuous", "spherical", current_Phot + 1);
	p1.totalDistTravelled(distsofarCyl, "continuous", "cylindrical", current_Phot + 1);
	p1.totalDistTravelled(distsofarPla, "continuous", "planar", current_Phot + 1);
       }while (current_Phot < cr1.photonNum);
      cout << "Continuous IR radiation simulation complete." << endl;
      free(mieAlbedo);
      free(wavelengths);
	free(energyLeft);
	free(KEMedium);
       /************************
       * NORMALIZE
         *   J[ir] escaping flux density [W/cm^2 per W incident]
		*   where bin = 2.0*PI*r[ir]*dr [cm^2].
		*   F[iz][ir]  fluence rate [W/cm^2 per W incident]
		*   where bin = 2.0*PI*r[ir]*dr*dz [cm^3].
		************************/
	temp = 0.0;
	for (ir = 0; ir < NR; ir++) {
	  r1 = (ir - 0.5)*dr;
	   temp += J[ir]; /* accumulate total escaped photon weight */
	J[ir] /= 2.0*PI*r1*dr*cr1.photonNum; /* flux density */
	 for (iz = 0; iz < NZ; iz++)
	F[iz][ir] /= 2.0*PI*r1*dr*dz*cr1.photonNum*totalSkinMua; 
       /* fluence rate */
		}
     specularReflec = Rsptot / cr1.photonNum;
	tabsorbedFrac = Atot / cr1.photonNum;
	tescapingFrac = temp / cr1.photonNum;
	Sptr = &specularReflec;
	Aptr = &tabsorbedFrac;
	Eptr = &tescapingFrac;
	/*SaveFile(int Nfile, double *J, double **F, double specularreflec, double absorbingFrac, double escapingFrac,double absorbCoeff, double scattCoeff, double anisG, double n1, double n2,int mcflag, double radius, double waist, double xs, double ys, double zs,int NR, int NZ, double dr, double dz, const int Nphotons);*/
	p1.SaveFile(NFile, J,(double**)F, specularReflec, tabsorbedFrac, tescapingFrac, totalSkinMua, avgSkinScattCoeff, skinAnis, cr1.ecm_refrac, cr1.air_refracIND, mcflag, radius, waist, xs, ys, zs, NR, NZ, dr, dz, cr1.photonNum);







I expect you've made a mistake with the indices. What is the size of the multi-dimensional array F? I bet you're trying to read/write an element that doesn't exist.
@Repeater F has a size 100 by 100 F[100][100]
When you call SaveFile(...) on line 116 you cast F (double**)F which might be illegal. Do not cast away compiler error.

Actually you do not show what the type of F is originally. So I cannot tell for sure whether that is the problem.

For instance double F[...][...] is not double**F

[EDIT]
This error is around a multidimensional array related to flux F[100][100]..see below.
You cannot cast it to (double**) because that is a pointer to a pointer and not an array
Last edited on
What is the value of NZ and NR? If NZ is 100 and NR is 100, you're trying to use F[100][100] which doesn't exist.
Topic archived. No new replies allowed.