广东话可用内存
在代码:广东话可用内存
template<class T,int row, int col>
void invert(T (&a)[row][col])
{
T* columns = new T[col * row];
T* const free_me = columns;
T** addresses = new T*[col * row];
T** const free_me_1 = addresses;
/*cpy addresses*/
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
*addresses = &a[i][j];
++addresses;
}
}
addresses = free_me_1;
/*cpy every column*/
for (int i = 0; i < col; ++i)
{
for (int j = 0; j < row; ++j)
{
*columns = a[j][i];
++columns;
}
}
columns = free_me;
/*cpy from columns to addresses*/
for (int i = 0; i < (col * row); ++i)
{
*addresses[i] = columns[i];
}
delete[] free_me_1;
delete[] free_me;
}
我观察到,尽管迭代,变量列的值为零,我认为这就是问题。
感谢您的帮助。
P.S.我粘贴了这个fnc的最终版本。它现在按预期工作。感谢大家的宝贵帮助。
因为缓冲区太小,所以您写过缓冲区末端。
T* columns = new T[col];
应该
T* columns = new T[col*row];
Writine了缓冲区到底是不确定的行为 - 你的情况是堆损坏,因为你覆盖了堆功能所必需的一些业务数据等delete[]
失败。
但是在什么时候? – 2010-04-02 09:51:34
谢谢,当然,我很害怕eejit。我会在10分钟内接受你的回答; – 2010-04-02 09:52:34
您将columns
初始化为new T[col]
。然后你增加内循环中的列,得到执行列*行时间 - 除非rows==1
,你增加列超过你分配的数组的末尾,导致未定义的行为。
请注意,即使一旦您解决这个问题,您的功能仍然是非常错误的 - 它既没有返回值也没有副作用。它应该是没有操作的。它绝对不会颠倒它的参数。
是的,我知道,这实际上只是这个fnc的一部分; – 2010-04-02 10:17:56
你是怎么调用这个函数的? – 2010-04-02 09:48:59
嗨,尼尔,我给我的帖子添加了对我的fnc的电话。 – 2010-04-02 09:50:20
您可能想要通过引用来获取数组,以便可以自动且正确地推导出所有模板参数:'T(&a)[row] [col]' - 否则您必须至少指定参数T和行,我认为。 – sellibitze 2010-04-02 09:56:22