Initializing a pointer to vector of pointer to string

Hello all,

How do I initializing a pointer to vector of pointer to string?
When I try this I get this for an error..

"Run-Time Check Failure #3 - The variable 'namesPtr' is being used without being initialized."

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
using std::string;

#include <vector>
using std::vector;


int main ()
{
	vector<string*>* namesPtr;
	namesPtr->push_back(new string("value"));
}
That's because namesPtr doesn't point to anything. Either vector<string*>* namesPtr = new vector<string*>(); or vector<string*>* namesPtr = &some_other_vector_of_pointers_to_strings;
Wow, that was fast and it worked. Thanks alot hamsterman!
Also note this isn't Java. You don't have to allocate everything with new. Here, I wouldn't recommend using pointers at all, as it just opens up the possibility of memory leaks and doesn't provide any real benefit.

A simple vector of string would be much simpler:

1
2
vector<string> foo;
foo.push_back("value");
Hi zaroth,
You can visit the vector to get one value like this:

examples:

namesPtr->push_back(new string("value0"));
namesPtr->push_back(new string("value1"));
namesPtr->push_back(new string("value2"));

std::cout << *(namesPtr->front()) << std::endl; //visit "value0"
std::cout << *(namesPtr->at(0)) << std::endl; //visit "value1"
std::cout << *(namesPtr->at(1)) << std::endl; //visit "value2"


Almost

1
2
3
std::cout << *(namesPtr->front()) << std::endl; //visit "value0"
std::cout << *(namesPtr->at(0)) << std::endl; //visit "value0", not "value1"
std::cout << *(namesPtr->at(1)) << std::endl; //visit "value1", not "value2" 



Of course if you don't use pointers, you can use the [] operator which is even easier ... and again, there really is no reason for the pointers here:

1
2
3
4
5
6
7
8
9
vector<string> names;

names.push_back("value0");
names.push_back("value1");
names.push_back("value2");

std::cout << names[0] << std::endl;  // print "value0"
std::cout << names[1] << std::endl;  // print "value1"
std::cout << names[2] << std::endl;  // print "value2" 
Topic archived. No new replies allowed.