How to have a unique array for each object

I have a program where I need to read in from a text file and use a character array to make a Word object. I want each Word object to have its own variable called charArray[]. So for example, if my text file says "This is a test", I would have 4 Word objects, the first would have (after Word word;) word.charArray[] == "This', the next == "is" etc. I wrote a program that sort of works, but it doesn't have a new charArray for each new object. That is if the first word is "This" printing word.charArray gives "This" but the second word is "is" yet word.charArray prints "isis" as in it overrides the "Th" from the last word but keeps the ending. I think this is probably something to do with me not understanding how the pointers are working in this case. But here is some of my code so you can take a look:
word.h:
1
2
3
4
5
class Word{
public:
    char charArray[];
//etc
};


word.cpp:
1
2
3
4
5
6
7
Word::Word(char array[]){
	int i = 0;
	while(array[i]){
		charArray[i] = array[i];
		i++;
	}
}


driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
	
        char charArray[50];
	string fileName = "test.txt";
	Word wordArray[20];
	int i = 0;
	int j = 0;
	int size = 0;
	ifstream myFile(fileName.c_str());
	if(myFile.is_open()){
		while(!myFile.eof()){
			myFile >> charArray;
			cout << charArray << "XXX" << endl;
			while(charArray[i]){
				size++;
				i++;
			}
			if(charArray[size - 1] == '.'){
				charArray[size - 1] = '\0';
			}
			cout << charArray << "XXX" << endl;
			Word word(charArray);
			wordArray[j] = word;
			j++;
			cout << word.charArray << "<- word.charArray" << endl;
			size = 0;
			i = 0;
				
		}
	}

The driver is my test code for a larger project, but each Word will eventually get put into a linked list which becomes one Sentence object. Thus for my test I'm just making an array of Word objects. I have to use character arrays and not strings for this project, in case you are wondering why I'm not simply using string.

So why does the charArray of Word remember the data from the previous Word, why is it not a unique array every time? Do I have to somehow clear the array or use dynamic allocation?
Topic archived. No new replies allowed.