Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector<char> to string segmentation fault

Tags:

c++

trying to initialize a string from a vector. I am supposed to get "hey" as the output. but I got "segmentation fault". what did I do wrong?

//write a program that initializes a string from a vector<char>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main ()
{
    vector<char> cvec;
    cvec[0]='h';
    cvec[1]='e';
    cvec[2]='y';
    string s(cvec.begin(),cvec.end());
    cout<<s<<endl;
    return 0;
}
like image 948
ihm Avatar asked Nov 11 '11 03:11

ihm


2 Answers

The vector class starts out with a size of zero (by default). So doing that will cause undefined behavior. (in your case, a segmentation fault)

You should use push_back() instead:

vector<char> cvec;
cvec.push_back('h');
cvec.push_back('e');
cvec.push_back('y');

This will append each char to the vector.

like image 184
Mysticial Avatar answered Sep 23 '22 00:09

Mysticial


You need to allocate space in the vector, like this:

vector<char> cvec(3);

Or push the characters in one by one:

vector<char> cvec;
cvec.push_back('h');
cvec.push_back('e');
cvec.push_back('y');
like image 22
John Zwinck Avatar answered Sep 23 '22 00:09

John Zwinck