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

Dynamic Array Using String Class

I am trying to load in a list of words into my program using a dynamic array and the string class....for some reason, all the tutorials are using char which i have no idea how to adapt to my code....

string *strWord;
	int Position = 0; 
	string strHolding;
	
	//for loading files
	ifstream fp_in;  // declarations of streams fp_in and fp_out
	ofstream fp_out;
	fp_in.open("WordList.WORD", ios::in);    // open the streams
	
	do {
		strWord = new string[Position];
		fp_in >> strWord[Position];
		Position =+ 1;
	}while (Position < 47);

	fp_in.close();   // close the streams
bryansworld
Newbie Poster
9 posts since May 2008
Reputation Points: 10
Solved Threads: 0
 

just some extra information....
i am able to run the program but when it gets to the string declaration it crashes and i get an access violation

bryansworld
Newbie Poster
9 posts since May 2008
Reputation Points: 10
Solved Threads: 0
 

Why don't you put some couts and check the values of 'Position' ? and btw you are leaking a lot of memory.

Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
 
... and btw you are leaking a lot of memory.

bryansworld, welcome to the world of C++ !

You're indeed leaking a lot of memory:
> What are you using variable 'strHolding' for ?
> Not very clever to insert the instruction strWord = new string[Position]; inside a loop as the program will always assign new memory and the old will still be allocated, but you don't have access to it anymore because you aren't having any pointer which is pointing to that memory ...

After you've rewritten your program:
> You shouldn't forget to release the allocated memory when it isn't needed anymore ...

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

BTW, Position =+ 1; is always setting variable Position to 1 ...

I think you meant Position += 1;

(if your intention was to increment variable Position each time with one)

As a result your program will throw itself into an infinite loop (*) where it's always allocating more and more and more ... memory which explains the crash ...

(*): You're always checking whether Position < 47 , but this is always true as Position =+ 1; is everytime setting Position's value to 1, and 1 is always lower than 47


I hope this explains your mistake(s) !

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You