954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

vector <char*>

Hi, i have a problem with a vector.

I declare a vector moves; in header.

Code:

void LogView::init(){
	int a = 0;
	while (LogFile.good()){
		LogFile.getline(line, 6);
		moves.push_back(line);
	cout << "vector :"<< moves[a]<< endl; // here is OK
	a++;
	}
	moves.begin();
	cout << "vektor :"<< moves[1]<< endl;  // here is NOT OK
	cout << "vektor :"<< moves[2]<< endl;  // here is NOT OK
	cout << "vektor :"<< moves[3]<< endl;  // here is NOT OK
	cout << "vektor :"<< moves.at(1)<< endl;  // here is NOT OK
	cout << "vektor :"<< moves.at(2)<< endl;  // here is NOT OK
	cout << "vektor :"<< moves.at(3)<< endl;  // here is NOT OK
	cout << "vektor :"<< moves.front()<< endl;  // here is NOT OK
	cout << "vektor :"<< moves.back()<< endl;  // here is NOT OK 
	//AN ITERATION FOR IS NOT OK TOO.
	cout << moves.size(); // IT'S OK!
	}
}


Thank You.

luisvega
Newbie Poster
9 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

How do you assing memory to each pointer?

Sci@phy
Posting Whiz in Training
279 posts since Sep 2008
Reputation Points: 110
Solved Threads: 43
 

Hi, in header:

private:
	std::ifstream LogFile;
	char line[5];
	std::vector<char*> moves;
luisvega
Newbie Poster
9 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

When you append pointers onto a vector of char, the pointer is copied. You are expecting the data the pointer points at to be copied.

With a vector you need to explicitly copy the data as well as the pointer.

An easier way would be to use a std::vector instead (as std::string objects copy the data implicitly).

grumpier
Posting Whiz in Training
211 posts since Aug 2008
Reputation Points: 193
Solved Threads: 32
 

Thank You!

luisvega
Newbie Poster
9 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You