2D vector declaration Seg fault core dump

Hi experts,
Please help, I do not know why this code Seg fault core dump.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
using namespace std;

const int n = 6;
const double num_g = 2914.0;
const double num_b = 177.0;
const double gb_ratio = num_g / (num_g + num_b);

vector<vector<double> > initProb( const int a) {
    vector<vector<double> > pi_mat(1, vector<double> (2*a));
    int i = 0; 
    int j = 0;
    for (; i < pi_mat.size(); i++) {
	if (i == 0) { 
	    pi_mat[i][0] = gb_ratio; 
	}//if
    } //for i

    int k = 0;
    int l = 0;

    for (; k < pi_mat.size(); k++) {
	for (; l < pi_mat[k].size(); l++) {
	    cout << pi_mat[k][l] << " ";
	}
	cout << endl;
    }

}//initProb

int main() {
    initProb(n);
    return 0;
}
Your routine initProb() is supposed to return something; it doesn't.

Add the line
return pi_mat;
before returning from the function.

Then turn the error-checking on for your compiler.
Last edited on
@lastchance
Thank you so much, sorry this is a really dumb question.
It was a simple error, @Beherit666.

You gave us the code, put it in code tags and stated the issue correctly - nobody can complain about that.

If you run the code in cpp.sh (little gear-wheel icon to top right of your code sample if it is runnable) then it will flag a lot of warnings/errors for you. You should be able to set various error-checking flags for your own compiler, too. (Though, that will vary from compiler to compiler).

Enjoy your coding.



@lastchance,
Sorry for late reply, thanks a lot for the instruction and reply. The cpp.sh is really awesome for a beginner like me. Happy holidays!
Registered users can post here. Sign in or register to post.