Array interfering where it shouldn't

I have a program where doing something to an array F changes another array D while to my eye it shouldn't matter to D at all. Here is the relevant code:

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
using namespace std;
#include <iostream>  
#include <stdio.h>    
#include <math.h> 

double bin(int, int);

int main() {	
	
	int i, j, k, s=100, t=15;
	double B[s], D[t*s-1], F[(t*(t+1))/2-1], A[t], theta[s];
	
	for(i=0;i<t;i++) A[i]=0.0;
	for(i=0;i<t*s-1;i++) D[i]=0.0;
	for(i=0;i<s;i++) {
		theta[i]=(double)i/(s-1.0);
		B[i]=sqrt(2.0)
	}
	
	for(j=0;j<t;j++) {
		for(k=0;k<=j;k++) {
			F[j*s+k]=sqrt(4.0*j+2.0)*(1.0-2.0*((j-k)%2))*bin(j+k, j-k)*bin(2*k, k);
			for(i=0;i<s-1;i++) {
				D[j*s+i]+=sqrt(4.0*j+2.0)*(1.0-2.0*((j-k)%2))*bin(j+k, j-k)*bin(2*k, k)*
				(pow(theta[i+1], 2*(k+1))-pow(theta[i], 2*(k+1)))/(2.0*(k+1.0));
			}
		}
	}
	
	for(j=0;j<t;j++) {
		for(i=0;i<s-1;i++) A[j]+=D[j*s+i]*B[i];
	}	
	
	cout << endl;
	for(i=0;i<t;i++) cout << "A_" << i << ": " << A[i] << endl;
	
	return 0;
}

double bin(int n, int m) {

	int i;
	double bin=1.0;
	if(m>n||m<0) return 0.0;
	else {
		for(i=1;i<=m;i++) {
			bin*=(double) (n-m+i)/i;
		}
	}
	return bin;
}


where 'bin' is a functon computing binomial coefficients. Now, the result I want is A[0]=1 and the rest of the A's zero. However this only works (to a pretty good precision) when I remove line 22 containing F. Do any of you see why this is?
Last edited on
The problem is:

The number of positions in array F is (t*(t+1))/2-1 = (15*(15+1))/2-1 = 119

In Line 22 of your code, the maximum index will be when j = t-1 = 14 and k = j = 14, this is, maximum index = j*s+k = 14*100+14 = 1414 which is way bigger than 119.
Last edited on
Thanks a lot! In line 22, instead of F[j*s+k]=... it should have been F[(j*(j+1))/2+k]=... How could I have missed that
Topic archived. No new replies allowed.