[英]Dynamic 2D array losing second dimension
I have a dynamically allocated, 2D array that is being populated within a pair of for loops. 我有一个动态分配的2D数组,该数组正在一对for循环中填充。 For some reason by the end of the for loops all of the elements are in inaccessible memory.
由于某些原因,在for循环结束时,所有元素都位于不可访问的内存中。
/*************Start Positive Phase*************************/
double *posHidActivations = new double[FEATURES];
memset(posHidActivations, 0, sizeof(double)*FEATURES);
double *posVisActivations = new double[m_NumRatings];
memset(posVisActivations, 0, sizeof(double)*m_NumRatings);
double **posProducts = new double*[FEATURES];
for(int i=0; i<FEATURES; i++)
posProducts[i] = new double[m_NumRatings];
for(int i=0; i<FEATURES; i++)
for(int j=0; j<m_NumRatings; j++)
posProducts[i][j] = 0;
/* manually verified elements are valid and
initialized to 0 with gdb */
// for each hidden node
for(int j=0; j<FEATURES; j++)
{
// sum up inputs from the visible layer
for(int i=0; i<m_NumRatings; i++)
{
double input = m_VisLayer[i]*m_Weights[i][j];
double prob = sigmoid(input, m_HidItemBias[j]);
posProducts[j][i] = m_VisLayer[i]*prob;
posVisActivations[j]+=m_VisLayer[i]; // commenting out this line fixes
posHidActivations[j]+=prob;
}
// posProducts[i][0] is valid here
}
/* posProducts[0][0] is a segfault
using gdp verified that posProducts is a valid double**
and posProducts[0] is a valid double*
Declarations for identifiers not in the previous snippit: 不在上一个代码段中的标识符的声明:
int m_NumRatings;
m_VisLayer = new double[m_NumRatings];
m_Weights = new double* [m_NumRatings];
for(int i=0; i<m_NumRatings; i++)
m_Weights[i] = new double [FEATURES];
m_HidItemBias = new double[FEATURES];
'FEATURES' is a #defined constant “功能”是#defined常量
Edit: I forgot to mention. 编辑:我忘了提。 Later in the program is a logically identical code block using different identifiers (posProducts -> negProducts, m_VisLayer -> m_HidLayer, etc).
在程序的后面是使用不同标识符(posProducts-> negProducts,m_VisLayer-> m_HidLayer等)的逻辑上相同的代码块。 That block does not show any of the same symptoms.
该阻止不会显示任何相同的症状。 I can't find any logical difference no matter how many times I compare the code.
无论我比较多少次代码,我都找不到任何逻辑上的区别。
As you note: 如您所述:
posVisActivations[j]+=m_VisLayer[i]; // commenting out this line fixes
The index for posVisActivations is j, which ranges from 0 to m_FEATURES, but posVisActivations is declared to be an array with m_numRatings elements. posVisActivations的索引是j,范围是0到m_FEATURES,但是posVisActivations声明为具有m_numRatings元素的数组。
So, you are writing past the end of the array. 因此,您正在写完数组的末尾。 You probably meant to use
i
as the index: 您可能打算使用
i
作为索引:
posVisActivations[i]+=m_VisLayer[i]; // commenting out this line fixes
HTH. HTH。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.