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

标签 c arrays struct segmentation-fault

我正在为我的研究编写一个程序,该程序需要一个不平凡的索引方案来处理自旋冰系统。为了帮助建立索引,我使用了结构体和数组的组合。每个结构体都包含一个立方单元内包含的 16 个点 [我试图发布立方单元的图片,但 stackoverflow 说我需要至少 10 个声誉点才能做到这一点,我很抱歉],但是由于数值原因,稍后这些需要存储在一个矩阵中。

决定系统大小(即模拟立方体有多大)的值在 L=1、L=2、L=3 时效果很好。但是,当我尝试 L=4 时,出现段错误。相关部分代码如下:

/* 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*LLL-1)

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

最佳答案

你的堆栈溢出了。将两个数组声明为静态数组:

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() 在堆上声明这些对象。

关于c - 涉及结构体和数组的段错误,但不分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24557527/

相关文章:

c++ - 在函数调用中定义一个匿名结构

c - Ising 1-Dimensional C - 程序

c - 信号错误: "invalid use of void expression"

copy_from_user - 难以从用户空间复制双指针

arrays - 如何在golang中访问struct中的一个 slice

c - 重新定义;不同的基本类型(typedef 结构)

C 研究元音和辅音 fork()

javascript - 将数组转换为对象数组

ruby - 在 Ruby 中删除相同的对象?

arrays - 如何检查数组中的所有值是否相同?