vector<const char *> *option

Hi,
I m beginner in c++. I m trying to shuffle the string to different positions in the vector array. I have written the code. Its giving the runtime error. Please help me out.

I m passing "hello", "mellow","jello","yello" if I do the "push_back" it automatically stores in the vector array positions at 0 1 2 3 respectively. But I want to store at 3 1 2 0 positions. Thanks in advance..

#include<stdio.h>
#include<conio.h>
#include<vector>
using namespace std;
void select(
const char *opt1, const char *opt2, const char *opt3, const char *opt4,int x )
{
const char *options[] = { opt1, opt2, opt3, opt4,NULL };
int y[4] = {3,1,2,0};
vector<const char *>::iterator it;
vector<const char *> *option;

for (int i = 0; options[i] != NULL ; i++)
{
int offset = y[i];
it = option->begin();
option->insert(it+offset,options[i]);

}

}

int main()
{
select("hello","mellow","jello","yello");
system("pause");
return 0;
}
vector<const char *> *option;

This is not a vector. It's a pointer. It doesn't actually point to anything.

Later, when you call insert (and begin), you are dereferencing a bad pointer and trying to insert elements to a non-existent vector. Hence the runtime error.

Furthermore, push_back would be much simpler than insert... since you're always adding to the end of the array... but that's a side issue.


For your main problem, use an actual vector object instead of a pointer:

1
2
3
4
5
6
7
8
9
10
vector<const char *> option;  // <- no *, so it's an object

//...

// now that you have an actual object, you can do this:
it = option.begin();
option.insert(it+offset, options[i]);

// or, more simply, this:
option.push_back( options[i] );
Disch thanks for the reply,

How do i initialize an array of char pointer using vector.

I tried using

vector<const char *> *option(options, options + sizeof(options)/sizeof(options[0]))

But it is giving the compiler error....
Last edited on
Get rid of that asterisk... that it making it a pointer. You do not want a pointer:

1
2
3
4
5
6
7
8
9
    vector<const char *> *option(options, options + sizeof(options)/sizeof(options[0]))
                         ^
                         |
                         |
                    Get rid of this


// correct:
    vector<const char *> option(options, options + sizeof(options)/sizeof(options[0]))
it worked thanks for the help...
Topic archived. No new replies allowed.