I'm trying to get a program to run here that will fill a dynamic array of class objects using pointers. From what I can tell from the errors (Unhandled exception at 0x00EE59A6 in Lab6take2.exe: 0xC0000005: Access violation reading location 0x00000014.) I've done something wrong with the pointer labelled songlist, as it seems to be pointing to zero. Here's the relevant code.
In the constructor of MP3Database you declare a local variable named songlist.
That means that you allocate memory to a temporary variable, and not the "real" songlist member data.
1 2 3 4 5
MP3Database :: MP3Database(int _size){
size = _size;
// MP3* songlist = new MP3[size];
songlist = new MP3[size];
}
So in the end the songlist member data was a bad pointer.
By the way, you didn't post the code for the ~MP3Database() destructor, so just in case you forgot:
1 2 3 4
MP3Database::~MP3Database()
{
delete[] songlist; // important to delete[] what was new[]'d
}
Additionally, the way you use the dynamic array songlist is weird and can lead to errors.
46 47 48 49 50 51
songlist->date = date;
// should use: songlist[x].date = date;
songlist++;
// bad, you alter the songlist pointer...
// you must not in order to delete[] it correctly
was what my lecturer recommended I do, and changing it to
songlist[i].setstars(stars);
doesn't seem to make any difference currently. The cin.ignore(); is the only thing that lets me enter text into the getline() function. Again, there doesnt seem to be any difference whether i use a getline() function or just regular old cin>> name;
At this point my suggestion would be that you post the full source code.
This is because the mistake (or mistakes) probably hide in the parts you did not yet post.
#include "MP3.h"
#ifndef class_MP3Database
#define class_MP3Database
class MP3Database{
public:
int size;
MP3* songlist = new MP3[size];
//MP3Database(); will not be implemented in the scope of the program
MP3Database(int);
void print();
void search(string);
void fillarray();
~MP3Database();
};
#endif
Copy-pasting the code which is problematic, below.
In these functions you use pointer arithmetic on the songlist member data.
By doing this, you alter the songlist member data, and it eventually turns into a bad pointer, hence the crashes.
So you must rewrite the for() loops to use songlist[i].??? as you did in the case of MP3Database::fillArray().
#include "MP3.h"
#ifndef class_MP3Database
#define class_MP3Database
class MP3Database{
public:
int size;
// MP3* songlist = new MP3[size]; // huh?
// does this not give at least a Warning? may be a C++11 feature though
MP3* songlist;
//MP3Database(); will not be implemented in the scope of the program
MP3Database(int);
void print();
void search(string);
void fillarray();
~MP3Database();
};
#endif