简体   繁体   English

for循环的分段错误

[英]Segmentation Fault from for loop

I have an old C code that I am updating into C++. 我有一个旧的C代码,正在更新为C ++。 I have changed all the arrays (pointers to arrays) into vectors. 我已经将所有数组(指向数组的指针)更改为向量。 There are multiple files involved in this code. 此代码中涉及多个文件。 The relevant pieces are below. 相关部分如下。

When I run it, I get a Segmentation Fault error on the first iteration calculating m[i] in fn.cpp. 运行它时,在第一次迭代中在fn.cpp中计算m [i]时遇到了Segmentation Fault错误。 If I define m outside of the statement, at its deceleration, I get the error on the w[i]. 如果我在语句之外定义m,则在减速度时,我会得到w [i]上的错误。 I'm unsure how to fix this 我不确定如何解决此问题

In the main.cpp file: 在main.cpp文件中:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <complex>
#include "fn.h"
using namespace std;

#include <gsl/gsl_rng.h>


// ===========================
// Variables
// ===========================
double eta = 0.13;
double w_max = 3;
int N_bath = 60;
vector<double> m(N_bath);
vector<double> c(N_bath);
vector<double> w(N_bath);

void main(){

bath_para(eta, w_max);

}

In the fn.h file: 在fn.h文件中:

#ifndef FUNCTIONS
#define FUNCTIONS

extern int N_bath;
extern vector<double> c;
extern vector<double> m;
extern vector<double> w;

#endif

In the fn.cpp file: 在fn.cpp文件中:

#include   <stdlib.h>
#include   <stdio.h>
#include   <math.h>
#include   <iostream>
#include   <complex>
#include   <vector>
#include   "fn.h"
using namespace std;

void bath_para(double eta, double w_max){

  double w_0;
  w_0 = (1 - exp(-w_max))/N_bath;

    for (int i = 0; i < N_bath; ++i){
        m[i] = 1.0
        w[i] = -log(1-(i+1)*w_0);
        c[i] = sqrt(eta*w_0*m[i])*w[i];
    }
}

You probably have an error somewhere else. 您可能在其他地方有错误。 With the following fn.h the code produce no errors (added declaration of both_para and namespace, which I assume you mistakenly removed as irrelevant): 使用以下fn.h,代码不会产生任何错误(添加了对para和namespace的声明,我认为您误认为它们是无关紧要的):

#ifndef FUNCTIONS
#define FUNCTIONS
using namespace std;
extern int N_bath;
extern vector<double> c;
extern vector<double> m;
extern vector<double> w;
void bath_para(double eta, double w_max);
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM