# Thread: Having a problem allocating space for an array of structures

1. ## Having a problem allocating space for an array of structures

When the code runs through the first time, it stores everything good into the first spot of the array but when it runs through the second time to get the input from the second line of the text file, it overwrites the stuff from the first run through.

I think it has to do with

NewArray = new Book;

but I don't know how to fix the logic on it.

TEXT FILE
Code:
```Harry Potter IV | J.K. Rowling | 747583 | DRAMA | PRINTED | 614 | false |
Lord Of The Rings | Jesse Moreland | 10011445 | DRAMA | AUDIO | true | 120 | Johnathon D. Smith |```
CODE
Code:
```		// Loops until the end of file
while(!myfile.eof())
{

// Read line of text file
char temp[128];
char * temp2 = "n";
myfile.getline(temp, 128, '\n');

// Allocate space in Book Array for another element
NewArray[counter] = new Book;

// Set all elements of struct book to read in file. I have to read in the whole line
// and set it to all the individual elements of book.
int i = 0;
while(i < 5)
{
temp2 = strtok( (i > 0 ? 0 : temp), "|");

if(i == 0)
strcpy(NewArray[counter].title, temp2);

else if (i == 1)
strcpy(NewArray[counter].author_name, temp2);

else if (i == 2)
strcpy(NewArray[counter].isbn, temp2);

else if (i == 3)
{
if(NewArray[counter].genre == 0)
NewArray[counter].genre = HORROR;

else if(NewArray[counter].genre == 1)
NewArray[counter].genre = SCIFI;

else if(NewArray[counter].genre == 2)
NewArray[counter].genre = COMEDY;

else if(NewArray[counter].genre == 3)
NewArray[counter].genre = DRAMA;

else if(NewArray[counter].genre == 4)
NewArray[counter].genre = ACTION;
}
else if (i == 4)
if(strcmp(temp2, " PRINTED ") == 0)
{
for(int j = 0; j < 2; j++)
{
temp2 = strtok(0, "|");
if( j == 0 )
NewArray[counter].media.hardcopy.num_pages = atof(temp2);
else if( j == 1)
NewArray[counter].media.hardcopy.paperback = temp2;
}
}
else if(strcmp(temp2, " AUDIO ") == 0)
{
for(int j = 0; j < 3; j++)
{
temp2 = strtok( 0, "|");
if( j == 0)
NewArray[counter].media.electronic.cd = temp2;
else if ( j == 1)
NewArray[counter].media.electronic.listening_time = atof(temp2);
else if (j == 2)
strcpy(NewArray[counter].media.electronic.narrator_name, temp2);
}
}
//increment i
i++;
}```

2. Code:
`NewArray[counter] = new Book;`
Perhaps you should increment counter.

3. Your gonna get an extra run checking eof like that; eof isn't set until after an attempt to read past the end of the file.

4. Why are you not using std::string and std::vector?