Hi,

I am getting the following error when I am trying to initialize a 2 dimensional vector with 0's.
I am not to figure out the reason. Any help is appreciated.

std::vector<int> truth_table;
        std::vector<vector<int> > truth_table_col;

        double no_of_twos = 7;
        double base_two = 2;
        
        cout << "No of 2's = " << no_of_twos << "\n";
        double combi = pow(base_two,no_of_twos)-1;

        for(int hfh=0; hfh<=(int)combi; hfh++)
        {
                for(int ghg=0; ghg<=(int)no_of_twos; ghg++)
                {
                        truth_table.push_back(0);
                }
                truth_table_col.push_back(truth_table);
                truth_table.clear();
        }

Program received signal SIGSEGV, Segmentation fault.
0xb7433aed in _int_malloc () from /lib/tls/libc.so.6

Thanks

1. You forgot to add std:: prefix for vector in template parameter.
2. Barbaric construct: hfh<=(int)combi . Make cast before loop.
This code works with VC++ 2008. Yes, it's a bad code: for example, you can initialize 2D vector in a simple, clear and effective manner:

truth_table.resize(n,0);
truth_table_col.resize(m,truth_table);
truth_table.clear();

This works great for me, using VC++ 2008 Express

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int main(int argc, char* argv[])
{
        std::vector<int> truth_table;
        std::vector<vector<int> > truth_table_col;

        double no_of_twos = 7;
        double base_two = 2;
        
        cout << "No of 2's = " << no_of_twos << "\n";
        double combi = pow(base_two,no_of_twos)-1;

        for(int hfh=0; hfh<=(int)combi; hfh++)
        {
                for(int ghg=0; ghg<=(int)no_of_twos; ghg++)
                {
                        truth_table.push_back(0);
                }
                truth_table_col.push_back(truth_table);
                truth_table.clear();
        }
        for(size_t i = 0; i < truth_table_col.size(); i++)
        {
            vector<int> &table = truth_table_col[i];
            for(size_t j = 0; j < table.size(); j++)
                cout << table[j] << " ";
            cout << "\n";
        }
}

Thanks.. the error is resolved......the suggestions are really helpful...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.