我知道其他地方已经问过这个问题,但我一直没有弄错。也许我做错了,因为这两个数组都在一个结构中。
(编辑:我从其他代码中获取结构,我无法更改它)
我正在尝试将两个float数组传递给一个函数,然后在第一个数组中保存操作结果。
core.h:
typedef struct{
//other stuff
float m_vector[16];
} structure_t;
class CoreClass{
private:
structure_t s1;
structure_t s2;
float *MyFunction(const float *vDest, const float *vNew);
}
core.cpp:
#include "core.h"
#include "another_file.h"
void anotherFunction(){
//....
s1.m_vector = MyFunction(s1.m_vector, s2.m_vector); //error here
//....
}
float *CoreClass::MyFunction(const float *vDest, const float *vNew){
return yet_another_function(vDest, vNew);
}
但是,当我调用该函数时,我收到此错误:
error: incompatible types in assignment of ‘float*’ to ‘float [16]’
为了完整性,这是我正在调用的函数,虽然它在编译时似乎没有任何麻烦:
another_file.h
static __inline float *yet_another_function(const float *vDest, const float *vNew){
float *tmp = new float[16];
//tmp = matrix multiplication (vDest * vNew)
for(int i=0; i<4; i++)
for(int j = 0; j<4;j++)
for(int k = 0; 4; k++)
tmp[i + j*4] += vDest[i + k*4] * vNew[k + j*4];
return tmp;
}
答案 0 :(得分:2)
问题是因为您正在为数组指定指针。在C ++中,您无法将指针指定给数组。
s1.m_vector = MyFunction(s1.m_vector, s2.m_vector);
^^ array ^^ return pointer
您可以使用从MyFunction
复制返回值到s1.m_vector
。
但是,为什么还需要重新分配值s1.m_vector
?您可以让MyFunction
函数在structure_t
中引用参考并在内部修改m_vector
。
void MyFunction(structure_t& vDest, const structure_t& vNew)
{
vDest.m_vector[0] = vNew.m_vector[0];
//...
vDest.m_vector[15] = vNew.m_vector[15];
}
修改
yet_another_function(structure_t* t, structure_t& vDest, const structure_t& vNew)
{
// blah blah
t->m_vector[i + j*4] += vDest.m_vector[i + k*4] * vNew.m_vector[k + j*4];
}
答案 1 :(得分:0)
看起来你返回指向float的指针并尝试将其保存到数组中。 structure_t.m_vector是一个数组而不是指针。
你可以像这样修理它:float * temp = MyFunction(s1.m_vector, s2.m_vector);
for(int i=0; i<16;i++)
s1.m_vector[i] = temp[i];
delete[] temp;
这仍然非常容易出错,如果你在yet_another_function中新增了16以外的其他大小,你就会遇到错误。作为一般规则,使用std :: array或std :: vector并按值返回将被建议。如果编译器支持c ++ 11,则按值返回的移动语义不会对性能造成损失。