6 months, 3 weeks 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 this library into a programITG3200

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

Post a comment on this question

3 Answers

 6 months, 2 weeks 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];

Accepted Answer
Post a comment on this answer
Tyler Weaver
poster
 6 months, 3 weeks 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];
   }
}

Great, mark it as accepted please.

posted by Tharshan M 31 Oct 2012
Post a comment on this answer
Tyler Weaver
poster
 6 months, 3 weeks 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);

Post a comment on this answer

To post an answer, please login