I am writing a C program to calculate Moving Average (MA) of share price. data is available in an array datavalue[count], count= is number of data values. Now i am trying to write up a function for MA.. but i have to pass three arguments in the function as follows
- int count = number of data values
- int K = period of moving average
- array float type datavalue = array containing share pricing.
I have written following code (as part of full code for calculation MA). it is working fine.
float data[count], mag[count];
double avg, sum;
for (i=0; i<=count; i++)
data[i] = numberArray[i];
for (i=0; i<k-1; i++) {
mag[i-1] = 0;
sum = sum + data[i];
}
for (i=k-1; i<=count; i++) {
mag[i-1] = avg;
sum = sum + data[i] - data[i-k];
avg = sum / k;
}
Above code is working fine within single main file. but as i have to reuse MA again and again in my program, thus i decided to make a separate function for MA. i did it as follows
float *mavg(int count, int k, float datavalue)
{
float *mag = malloc(sizeof(float)*count);
//float data[count];
float avg=0, sum=0;
int i;
for (i=0; i<=count; i++) {
for (i=0; i<k-1; i++) {
mag[i-1] = 0;
sum = sum + datavalue[i];
}
}
for (i=k-1; i<=count; i++) {
mag[i-1] = avg;
sum = sum + datavalue[i] - datavalue[i-k];
avg = sum/k;
}
return mag;
}
BUT above code is not working when calling from main file. While compiling it is showing error
subscripted value is neither array nor pointer nor vector
in following lines :
sum = sum + datavalue[i];sum = sum + datavalue[i] - datavalue[i-k];
datavalueis declared as a single float. You can’t use it as an array. You probably wanted to declare it as a pointerfloat datavalue)datavalue[i]