Go Down

Topic: Problem passing function argument as reference (Read 1 time) previous topic - next topic

Matous

Hi!
I think, that Arduino should support this normally, since it is the C++ standard, so I am probably just missing some stupid mistake...
But I'm pretty stuck on this. So - I have this neat function, that just reads some data from the mouse, I am interfacing and saves them into the arguments sent to it. Or it should do so... The problem is not the reading (Serial.print() inside this function gives me the correct data without problems), but the process of copying the values into the arguments (Serial.print() after the function gives me zero).

Here is a simplified code:

Code: [Select]

void get_mouse_data(int& mstat, int& left_encoder, int& right_encoder)

void setup(){}

void loop()
{
int mstat = 0;
int l_enc = 0;
int r_enc = 0;

get_mouse_data(mstat, l_enc, r_enc);

Serial.print("LENC: ");
Serial.print(l_enc);
Serial.print(",RENC: ");
Serial.println(r_enc);
  //this gives me zeros (rarely something, that doesn't make sense...) :(
}

void get_mouse_data(int& mstat, int& left_encoder, int& right_encoder)
{
int data[2] = {0};
mouse->report(data);
mstat = data[0];
right_encoder = -data[1];
left_encoder = -data[2];

Serial.print("LENC: ");
Serial.print(left_encoder);
Serial.print(",RENC: ");
Serial.println(right_encoder);
  //this gives me correct data
}


I did even try it with pointers... Didn't help. What am I missing here?
Thanks for any tips!

PaulS

Gives you what problems?

Code: [Select]
int data[2] = {0};
mouse->report(data);
mstat = data[0];
right_encoder = -data[1];
left_encoder = -data[2];

You are declaring a local array with 2 elements, and initializing one of them. The other contains random garbage.

Then, you call a function that might, or might not, overwrite those 2 values.

Finally, you assign the 2nd and 3rd (of 2) of them to variables.

Matous

Well... Actually the command
Code: [Select]

int data[2] = {0};

initializes the whole array, not just the first element.

But as you correctly pointed out, it creates an array of two elements, which is the problem...
Thanks for your fast answer, I didn't see this one by myself!

guix

Can someone tell me why the sscanf function (for example) require that we pass referenced parameters with a '&' in front of them, like:
Code: [Select]

sscanf( str, "%d", val); // doesn't work

sscanf( str, "%d", &val); // work

Arrch


Can someone tell me why the sscanf function (for example) require that we pass referenced parameters with a '&' in front of them, like:
Code: [Select]

sscanf( str, "%d", val); // doesn't work

sscanf( str, "%d", &val); // work



Because the sscanf function parses data from the provided string and stores it in val. If you don't pass a reference to the variable val, then sscanf has no way of changing the contents of val.

Go Up