Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
12 years ago.
Handing a function that returns a pointer to an array?
I'm trying to get the values out a function with the prototype:
const int* getOffset( ) const
The function returns a pointer to an array of 3 integers.
The code I wrote to retrieve the values is:
int gyro_readings[3]; gyro_readings[0] = *gyro.getOffset(); gyro_readings[0] = *(gyro.getOffset()+1); gyro_readings[0] = *(gyro.getOffset()+2);
The first value is as expected, the second two are not. Please help.
This is in reference to calibrating for Thermal Drift on the ITG3200 gyro with use of this library:
Import libraryITG3200
Forked from Aaron Berk's ITG3200 driver class library, customized for my specific application using 9DoF-Stick by Sparkfun.
See: http://mbed.org/users/gltest26/code/ITG3200/wiki/Thermal-Drift?c=4239
3 Answers
12 years ago.
Did you mean to write this? :
int gyro_readings[3]; gyro_readings[0] = *gyro.getOffset(); gyro_readings[1] = *(gyro.getOffset()+1); gyro_readings[2] = *(gyro.getOffset()+2);
There's nothing wrong with doing it that way, but it does mean calling the getOffset method three times. Also, you can treat a pointer exactly like an array so you could write:
int gyro_readings[3]; const int *readings = gyro.getOffset(); gyro_readings[0] = readings[0]; gyro_readings[1] = readings[1]; gyro_readings[2] = readings[2];
12 years ago.
I solved my problem by modifying the function in the library from:
const int *getOffset()const{ return offset; }
to:
void getOffset(int offset_copy[3])const{ if(offset_copy) { for(int i = 0; i < 3; i++) offset_copy[i] = offset[i]; } }
12 years ago.
I'm sure my problem is just as a result of my own lack of knowledge of C/C++. Does anyone have an example of how to make it work without modifying the library.
This was an idea I had, but it didn't work:
int *ptr = gyro.getOffset(); for(int i = 0; i < 3; i++) gyro_readings[i] = *(ptr+i);