jeudi 30 juin 2016

C++ Segmentation Fault Passing Class Variables to Class Functions

So I'm trying to have a class variable that is a vector and pass it in between some class functions. A basic version of what I'm trying to do is captured in the following:

#include <iostream>
#include <string>
#include<stdlib.h>
#include <vector>
using namespace std;


class isingModel {
    private:
        int length;

    public:
        void set_values (int);
        void ising_Iterator(vector<vector<int> > & );
        vector<vector<int> >  lattice;
};


void isingModel::set_values (int l) {
    length = l;
    vector<vector<int> > lattice(length, vector<int>(length));

    for (int i=0;i<length;i++){
        for (int j=0;j<length;j++){
                int randNum = rand() % 2; // Generate a random number either 0 or 1
                lattice[i][j]=2*(randNum-.5); //shift value so that it is either 1 or -1.
        }
    }
}

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}



int main () {
    int L;
    cout << "Enter the length of the lattice: ";
    cin >> L;

    isingModel iModel;

    iModel.set_values(L);
    iModel.ising_Iterator(iModel.lattice );
    return 0;
}

So I have a class that has some functions, but my main goal is to make a class variable vector and then pass it to different class functions. In this code I make vector called lattice and set it's values in set_values and then after passing lattice to ising_Iterator by reference and want to change some values in lattice. According to the documentation and other questions I thought I would have to pass the vector by reference (hence the & in the function declaration). But I seem to still getting segmentation fault. I used gdb to discover that the problem is in ising_Iterator, so it must be that the class function ising_Iterator does not have access to the lattice vector. One of the reasons I'm so confused is that if I replace

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}

with

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    length=1;

}

everything compiles and runs fine. So I've concluded that passing class variables that are vectors to class functions and changing them is fundamentally different then just passing class variables to class function and changing them there..

Aucun commentaire:

Enregistrer un commentaire