组数组复制到多维数组

问题描述:

我想了解C/Arduino的指针,它给我的问题:)组数组复制到多维数组

我有一个创建并返回一个指向float数组中的函数:

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

我还定义多维数组:

float data[2][2]; 

之前,我做任何事情,我期待的数据是这样的:(它一定支持)

0 0 
0 0 

当我运行下面的代码:

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

我预计的数据是这样的:

0 0 
23 24 

但它看起来是这样的:

0 0 
23 0 

不知何故,创建的数组是float [2]的信息丢失了,当我tr时y以投它漂浮[2]我得到:

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

你是返回地址,当你走出去的范围被删除本地变量 – 2014-12-07 20:16:50

+0

*数据[1]相同的数据[1] [0]。 *数组与数组[0]相同。如果你想复制整个数组,你需要循环或使用memcpy()。 – warsac 2014-12-07 20:18:19

+0

啊当然,这是有道理的超出范围 – happy 2014-12-07 21:02:24

而是使用从堆栈上的本地定义原始返回数组的指针,你必须使用一个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; 
} 

这应该可以解决所有关于未定义行为你的问题,因为在formerly marked duplicate指出了这个问题。