I'm quite new to c++, and this is the first time i've used vectors so please bear with me;)
I have a vector that stores objects of class Note. I can push_back and retrieve objects just fine except for one case, where I'm trying to get not the current object but the previous object in a for-loop. Here is the complete code, with the section I believe to be the culprit marked with comments: http://pastebin.org/154570
int charFind(char array[], char val) {
int length = (sizeof(array)/sizeof(char)); //Error -cannot calculate the size of an array like this when it is passed as a function parameter
int cnt;
for (int i = 0; i < length; i++) {
char a = array[i];
if (a == val) {
break;
}
else {
cnt++;
}
}
return cnt;
}
int charFind(char array[], int length, char val) {
int cnt;
for (int i = 0; i < length; i++) {
char a = array[i];
if (a == val) {
break;
}
else {
cnt++;
}
}
return cnt;
}
The same goes for the intFind(). I wasnt aware that you couldn't calculate the size that way if it is passed as an argument, so thanks for that;) But still the program crashes...
scanf("%d", &length);
vector<Note> melody; // Create an empty vector
for (int i = 0; i < length; i++) {
Note n;
if (i == 0) {
n.setPitch(majorScale[rand()%sSize]);
n.setDuration(durations[rand()%dSize]);
}
elseif (i > 0) {
int pIndex;
int dIndex;
//Appears to be problem area
//Severe carsh here!!
//melody vector is still empty (it has no Note objects in it yet)
//and we are trying to access a Note object at melody[i-1]
//Fatal Error
pIndex = charFind(majorScale, melody[i-1].getPitch());
dIndex = intFind(durations, melody[i-1].getDuration());
//End of problem area
//Pitch
if (pIndex == 0)
can I assume that what you rare trying t to do is to check if a partcicular Note already exist in
the vector or something similar??
It would perhaps appear so from the code that I posted, but the n-object is added to the vector at the end of the for-loop, just after the else if-statement. So the note is/should be in the vector. Here is the complete code: http://pastebin.org/155016
In the intFind and charFind functions - the variable cnt is not correctly used.
It is not initialised - so cnt++ is effectively random - so you are returning a garbage value.