段错误涉及结构和数组,但不是分开的

时间:2014-07-03 15:16:46

标签: c arrays struct segmentation-fault

我正在为我的研究编写一个程序,需要一个非平凡的索引方案来处理旋转冰系统。为了帮助编制索引,我使用了结构和数组的组合。每个结构都包含一个立方体单元格中包含的16个点[我试图发布一个立方体单元格的图片但是stackoverflow表示我需要至少10个声誉点这样做,我的道歉],但是由于数值原因以后这些需要存储在一个矩阵中。

确定系统大小的值(即模拟立方体有多大)在L = 1,L = 2,L = 3时工作正常。但是,当我尝试L = 4时,我有一个seg错误。代码的相关部分如下:

/* The indexing of this program is as 
 *  (i,j,k) refers to which cubic cell you are in 
 *  (l,m) refers to which particle in the cubic cell you are in 
 *  the order is as follows
 *  (l,m) = (1,1) (1,3)   (3,1) (3,3)
 *          (1,0) (1,2)   (3,0) (3,2)
 * 
 *          (0,1) (0,3)   (2,1) (2,3)
 *          (0,0) (0,2)   (2,0) (2,2)
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define FOR_IJKLM for (i=0; i<L; i++) \
                    for (j=0; j<L; j++) \
                      for (k=0; k<L; k++) \
                        for (l=0; l<4; l++) \
                          for (m=0; m<4; m++)

// L  := integer length of convential cubic cell
// Np := Number of total particles in the system
#define L   4
#define Np  16*L*L*L

struct ConventialCube{
  double p[4][4][3];   // Position of particle 
  double mu[4][4][3];  // Magnetic Moment of particle
};

void initialize(struct ConventialCube cc[][L][L]);

int main(void){
  struct ConventialCube cc[L][L][L]; 
    initialize(cc); 

  double ewaldMatrix[Np][Np];

  return 0;
}

void initialize(struct ConventialCube cc[][L][L]){
  int i, j, k, l, m, d;
  double s = 1.0/sqrt(3);

  double sv[4][3] = {
    {-s,-s,-s},
    {-s, s, s},
    { s,-s, s},
    { s, s,-s}
  };
  double O[4][3] = {
    {0.0, 0.0, 0.0},
    {0.0, 0.5, 0.5},
    {0.5, 0.0, 0.5},
    {0.5, 0.5, 0.0}
  };

  FOR_IJKLM{
    double CO[] = {i,j,k};
    for (d=0; d<3; d++){
      cc[i][j][k].mu[l][m][d] = sv[m][d];
      cc[i][j][k].p[l][m][d] = CO[d] + O[l][d] + O[m][d]/2.0;
    }
  }
}

如前所述,代码运行L = 1,L = 2,L = 3,但是在L = 4时它会中断。我发现的一些特点如下:

  • 注释掉ewaldMatrix阵列将允许L = 4运行
  • 将ewaldMatrix更改为整数类型将允许L = 4运行
  • 注释掉initialize(cc)行将允许代码运行
  • 用少一个数据点编写Np将允许它运行(即将Np定义为 16 * L L-1)

我非常感谢任何输入或建议,因为L = 4的情况是绝对必要的(我实际上并不需要高于L = 4的任何东西,只有L = 4 - 我猜的是Murphy的定律)。

1 个答案:

答案 0 :(得分:2)

你堆满了。将两个数组声明为static:

int main(void){
    static struct ConventialCube cc[L][L][L]; 
    initialize(cc); 

    static double ewaldMatrix[Np][Np];
    return 0;
}

或全局:

static struct ConventialCube cc[L][L][L]; 
static double ewaldMatrix[Np][Np];

int main(void){
    initialize(cc); 
    return 0;
}

或者,您也可以使用malloc()在堆上声明这些对象。