3

I am trying to understand pointers in c/arduino, and its giving me problems :)

I have a function that creates and returns a pointer to an array of floats:

float* CreateArray(int i) {
    float test[2];
    test[0] = float(i+1); 
    test[1] = float(i+2);
    return test;
}

I have also defined a multidimensional array:

float data[2][2];

Before I do anything I expect data to look like this: (which it does)

0 0
0 0

When I run the following code:

float* array = CreateArray(22);
*data[1] = *array;

I expect data to look like this:

0  0
23 24

But it looks like this:

0  0
23 0

Somehow the information that the created array was a float[2] is lost, and when I try to cast it to float[2] I get:

ISO C++ forbids casting to an array type 'float [2]'
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
happy
  • 33
  • 3
  • 3
    You are returning an address to local variable which is deleted when you go out of scope – Jens Munk Dec 07 '14 at 20:16
  • *data[1] is the same as data[1][0]. *array is the same as array[0]. If you want to copy whole arrays you need to loop or use memcpy(). – warsac Dec 07 '14 at 20:18
  • ah yes of course that makes sense its out of scope – happy Dec 07 '14 at 21:02
  • @happy I well receive you accept my answer to solve your problems. If you have any additional questions or problems, don't hesitate to ask, and point me to another question perhaps. – πάντα ῥεῖ Dec 07 '14 at 21:29

1 Answers1

0

Instead of using a pointer returned from a locally defined raw array on the stack, you must use a std::array to make the returned values accessible:

std::array<float,2> CreateArray(int i) {
    std::array<float,2> test;
    test[0] = float(i+1); 
    test[1] = float(i+2);
    return test;
}

This should fix all of your problems regarding undefined behavior, as stated in the formerly marked duplicate to this question.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190