Set array of float arrays to multidimensional array

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

I have a function that creates and returns a pointer to a float array:

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

      

I also defined a multidimensional array:

float data[2][2];

      

Before doing anything, I expect the data to look like this: (which is what it does)

0 0
0 0

      

When I run the following code:

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

      

I expect the data to look like this:

0  0
23 24

      

But it looks like this:

0  0
23 0

      

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

ISO C++ forbids casting to an array type 'float [2]'

      

+3


source to share


1 answer


Instead of using a pointer returned from a locally defined raw array on the stack, you should use to make the return values ​​available: std::array

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 indicated in the previously noted duplicate to this question.

0


source







All Articles