Exception thrown at 0x00509159 in FA.exe: 0xC0000005: Access violation reading location 0x0040400C.

This is my typedef struct
1
2
3
4
5
6
7
typedef struct
{
	char date[11];
	double price;
	double SMA;
	double EMA;
}DATA;


This is the function that has error. When i used debugger, Exception thrown at 0x00509159 in FA.exe: 0xC0000005: Access violation reading location 0x0040400C. was shown at line at price_total += forex[i].price;.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void calculate_SMA(int time_frame, int count, DATA forex[])
{
	double sma, price_total;
	for (int j = time_frame - 1; j < count; j++)
	{
		price_total = 0.0;

		for (int i = 0; i < i + time_frame; i++)
			price_total += forex[i].price;
		
		forex[j].SMA = price_total / time_frame;
		cout << forex[j].SMA << endl;
	}
}
Last edited on
forex[i].SMA is an array of doubles. Ten double objects, in an array.

price / time_frame is a single value. One single number.

Do you see the problem?


Also, why not switch to C++?
This is old-school C:
1
2
3
4
5
6
7
typedef struct
{
	char date[11];
	char price[10];
	double SMA[10];
	double EMA[10];
}DATA;


This is (bad) C++:
1
2
3
4
5
6
7
struct DATA
{
	char date[11];
	char price[10];
	double SMA[10];
	double EMA[10];
};


This is better C++:
1
2
3
4
5
6
7
struct DATA
{
	string data;
	string price;
	vector<double> SMA;
	vector<double> EMA;
};



Although why is price in the struct at all? It's a number, you use it as a number, you never actually use the price value in the struct; why does it exist at all in the struct?

Why is SMA and EMA ten objects, instead of just one? Why is it not this?

1
2
3
4
struct DATA
{
	double SMA;
};

which is everything being used. Which raises the question, why does this struct exist at all?
Last edited on
@Repeater I have changed the code slightly, please help with the new error...
> for (int i = 0; i < i + time_frame; i++)

How do you expect this loop to ever exit?

oh yeah... but how can i make it increase accordingly everytime my i increase, for example, if my time_frame=5, i want the loop to add all numbers from array index 0 to 4, then for the second time, i want the loop to add all the numbers from array index 1 to 5
Dunno - is this what you want?
for (int i = j; i < j + time_frame; i++)

If you don't use j at all in your inner loop, then that's as good as saying that the inner loop is constant (an invariant).
Topic archived. No new replies allowed.