sroy10
1
Hi,
I'm trying to pass 2 arrays to a function and sum the elements of each arrray. However, I am getting an error code.
float Sxyz[] = {1.1,2.0,3.25};
float Txyz[] = {2.0,4.45,6.75};
float Nxyz[3];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
MirrorNormal(Sxyz[],Txyz[],Nxyz[]);
delay(1000);
}
void MirrorNormal(float Sunxyz, float Targetxyz, float ReturnNormal){
ReturnNormal[0] = Sunxyz[0] + Targetxyz[0];
ReturnNormal[1] = Sunxyz[1] + Targetxyz[1];
ReturnNormal[2] = Sunxyz[2] + Targetxyz[2];
Serial.print(ReturnNormal[0]);Serial.print(",");
Serial.print(ReturnNormal[1]);Serial.print(",");
Serial.println(ReturnNormal[2]);
}
This is the error I am getting:
^
exit status 1
expected primary-expression before ']' token
guix
2
Why are you passing global variables to a function ?
sroy10
4
If I create a local variable, how do I return the value? This is demo code whose frame work I will use for a larger code
In the normal way, or you could change a global variable. In the code snippet that you posted you did not return a value anyway
Don't pass the array, pass a pointer or reference to it. For example:
float Sxyz[] = {1.1,2.0,3.25};
float Txyz[] = {2.0,4.45,6.75};
float Nxyz[3];
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// put your main code here, to run repeatedly:
MirrorNormal( Sxyz, Txyz, Nxyz );
Serial.print(Nxyz[0]);Serial.print(",");
Serial.print(Nxyz[1]);Serial.print(",");
Serial.println(Nxyz[2]);
delay(1000);
}
void MirrorNormal(float *Sunxyz, float *Targetxyz, float *ReturnNormal)
{
*ReturnNormal = *Sunxyz + *Targetxyz;
*(ReturnNormal+1) = *(Sunxyz+1) + *(Targetxyz+1);
*(ReturnNormal+2) = *(Sunxyz+2) + *(Targetxyz+2);
}
Why make things so obscure?
void MirrorNormal(float Sunxyz[], float Targetxyz[], float ReturnNormal[])
{
ReturnNormal [0] = Sunxyz[0] + Targetxyz[0];
ReturnNormal [1] = Sunxyz[1] + Targetxyz[1];
ReturnNormal [2] = Sunxyz[2] + Targetxyz[2];
}
1 Like
Or pass the number of elements so the same function can be used with arrays of different sizes:
MirrorNormal(3, Sxyz, Txyz, Nxyz);
void MirrorNormal(size_t count, float Sunxyz[], float Targetxyz[], float ReturnNormal[])
{
for (size_t i=0; i< count; i++)
ReturnNormal [i] = Sunxyz[1] + Targetxyz[1];
}
And you can make it a function template so it works on arrays of different types, not just 'float'. I think that would look something like:
MirrorNormal<float>(3, Sxyz, Txyz, Nxyz);
void MirrorNormal<T>(size_t count, T Sunxyz[], T Targetxyz[], T ReturnNormal[])
{
for (size_t i=0; i< count; i++)
ReturnNormal [i] = Sunxyz[1] + Targetxyz[1];
}
Did you mean [1] here or [i] ?
OOPS! Yes:
ReturnNormal [i] = Sunxyz[i] + Targetxyz[i];
1 Like
system
Closed
11
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.