I was writing a C program to calculate the Spearman Coefficient. It works fine but when I use
*spearmanCoefficient = coeff; I get this output: Spearman: 0.01
and when I use
spearmanCoefficient = &coeff; I get this output: Spearman: 15707109983512927750860237824432537600.00
However, correlationFlag = &corrFlag; gives me the correct output.
If I understand correctly, the first statement assigns the value of the variable coeff to the value of the pointer spearmanCoefficient and the second statement assigns the address of the variable coeff to the pointer spearmanCoefficient which should result in the same output but the output suggests that the second statement is referencing the address of the variable and not its value.
Can anyone explain why this is happening? Thank you.
Source code:
#include <stdio.h>
#include <math.h>
_Bool Correlate (int size, float arrayOne[], float arrayTwo[], float *spearmanCoefficient, float *correlationFlag)
{
if (size > 0) {
float sumOne = 0.0f;
float sumTwo = 0.0f;
for (int i = 0; i < size; i++) {
sumOne = sumOne + arrayOne[i];
sumTwo = sumTwo + arrayTwo[i];
}
float meanOne = sumOne / (float)size;
float meanTwo = sumTwo / (float)size;
float varianceOne = 0.0f, varianceTwo = 0.0f;
for (int i = 0; i < size; i++) {
sumOne = sumOne + pow((arrayOne[i] - meanOne), 2);
sumTwo = sumTwo + pow((arrayTwo[i] - meanTwo), 2);
}
varianceOne = sumOne / (float)size;
varianceTwo = sumTwo / (float)size;
float coeff = 0.0f;
float corrFlag = 0.0f;
for (int i = 0; i < size; i++) {
coeff = coeff + (((arrayOne[i] - meanOne) * (arrayTwo[i] - meanTwo)) / (size * sqrt(varianceOne * varianceTwo)));
}
spearmanCoefficient = &coeff;
if (coeff >= 0.9 && coeff <= 1.0) {
corrFlag = 1.0;
} else if (coeff >= -1.0 && coeff <= -0.9) {
corrFlag = -1.0;
} else {
corrFlag = 0.0;
}
correlationFlag = &corrFlag;
return 1;
}
else {
return 0;
}
}
int main() {
float arrayOne[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
float arrayTwo[10] = {4.0, 6.0, 9.0, 10.0, 2.0, 3.0, 5.0, 5.0, 6.0, 8.0};
int size = 10;
float *spearmanCoefficient;
float *correlationFlag;
_Bool var = Correlate(size, arrayOne, arrayTwo, spearmanCoefficient, correlationFlag);
printf("Spearman: %.2f\n", *spearmanCoefficient);
printf("Flag: %.2f\n", *correlationFlag);
return 0;
}