动态2D阵列失去第二维

时间:2011-05-08 11:45:06

标签: c++ multidimensional-array

我有一个动态分配的2D数组,它正在一对for循环中填充。由于某些原因,在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*

不在上一个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'是#defined常量

编辑:我忘了提。在程序的后面是使用不同标识符的逻辑上相同的代码块(posProducts - &gt; negProducts,m_VisLayer - &gt; m_HidLayer等)。该块没有显示任何相同的症状。无论我比较代码多少次,我都找不到任何逻辑差异。

1 个答案:

答案 0 :(得分:4)

正如您所说:

posVisActivations[j]+=m_VisLayer[i];   // commenting out this line fixes

posVisActivations的索引是j,范围从0到m_FEATURES,但posVisActivations被声明为具有m_numRatings元素的数组。

所以,你正在写过数组的末尾。您可能打算使用i作为索引:

posVisActivations[i]+=m_VisLayer[i];   // commenting out this line fixes

HTH。