-1

This is a bit code i'm having trouble with:

int pressedKey = event.getNativeKeyCode();

for (int i=0; i <= AllTriggerPads.size() ;i++) {
    if (AllTriggerPads[i]->get_key() == pressedKey){
        AllTriggerPads[i]->mBufferPlayerNode->start();
    }
}

the get_key() is getting a EXC_BAD_ACCESS (Code=1, ...) Error.

I seem to have a referencing problem. I am using almost the same code in the mouseDown and the fileDrop function:

for (int i=0; i < AllTriggerPads.size() ; i++) {

    if (AllTriggerPads[i]->mRect.contains(event.getPos())) {
        AllTriggerPads[i]->mBufferPlayerNode->start();
    }
}

This works fine!

Sooooo, i guess i am using the AllTriggerPads vector (of obj pointers) not correctly. So I CAN use AllTriggerPads[i]->mRect.contains(event.getPos()) but I CANT use AllTriggerPads[i]->get_key(). And I CANT access the value itself by AllTriggerPads[i]->key I have tried it with AllTriggerPads.at(i) but then i get an out of range error which makes me wonder even more.

The AlltriggerPads was initialized with vector<TriggerPad*> AllTriggerPads;

So how can I access the key member?

  • `i <= AllTriggerPads.size()` is wrong. You should have an index that is less than size actually: `i < AllTriggerPads.size()`. Voting to close, because that's just a simple and basic error/misconception. – πάντα ῥεῖ Jun 30 '15 at 17:47

2 Answers2

3

You are having an off-by-one error.

for (int i=0; i <= AllTriggerPads.size() ;i++)

replace with

for (int i=0; i < AllTriggerPads.size(); ++i)

(The ++ thing is irrelevant, it's just better practice to always use pre-increment)

KABoissonneault
  • 2,359
  • 18
  • 17
  • Oooooh, so der was no Object found at AllTriggerPads[0] ??? what is pre-increment anyway? Does it increment the counter before it does the { ... } part ? – Steffen Jun 30 '15 at 17:44
  • @Steffen No, you got it wrong. There was an object at AllTriggerPads[0]. It's at AllTriggerPads[AllTriggerPads.size()] that there is no object: never, ever will there be an object at the index == size. And in this particular case, pre-increment does nothing different from post-increment, except that it's "faster" (your compiler might optimize it to the same for the type int, but for iterators it might not) – KABoissonneault Jun 30 '15 at 17:55
1

You are trying to access an array element which doesn't exist. That's why it throws EXC_BAD_ACCESS. Change the for loop conditional to

for (int i = 0; i < AllTriggerPads.size(); ++i) {
    if (AllTriggerPads[i]->get_key() == pressedKey) {
        AllTriggerPads[i]->mBufferPlayerNode->start();
    }
}

or if C++11 support is enabled, simplify it to

for (auto i : AllTriggerPads) {
    if (i->get_key() == pressedKey) {
        i->mBufferPlayerNode->start();
    }
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50