-1

I'm getting a 'vector subscript out of range' error. I know this is caused by an indexing issue where the index is larger than the maximum size of the array/collection. However, I can't figure out why it's getting to that stage, as I am only ever incrementing the value by one, once in the entire project, and if it becomes larger than the size of the array, I reset it to 0. This is in regards to the frames of an animation in SDL. The index variable in question is m_currentFrame.

Here is the 'Process' method for the animated sprite, this is the only place in the entire project that calls 'm_currentFrame++', I did a ctrl+f search for it:

    void
AnimatedSprite::Process(float deltaTime) {
    // If not paused...
    if (!m_paused){
        // Count the time elapsed.
        m_timeElapsed += deltaTime;
        // If the time elapsed is greater than the frame speed.
        if (m_timeElapsed > (float) m_frameSpeed){
            // Move to the next frame.
            m_currentFrame++;

            // Reset the time elapsed counter.
            m_timeElapsed = 0.0f;

            // If the current frame is greater than the number 
            //          of frame in this animation...
            if (m_currentFrame > frameCoordinates.size()){
                // Reset to the first frame.
                m_currentFrame = 0;

                // Stop the animation if it is not looping...
                if (!m_loop) {
                    m_paused = true;
                }

            }

        }
    }   
}

Here is the method (AnimatedSprite::Draw()), that is throwing the error:

    void
AnimatedSprite::Draw(BackBuffer& backbuffer) {      
    //          frame width
    int frameWidth = m_frameWidth;

    backbuffer.DrawAnimatedSprite(*this, frameCoordinates[m_currentFrame], m_frameWidth, m_frameHeight, this->GetTexture());
}

Here is a screenshot of the exact error:

error

ninja
  • 11
  • 2
  • You should use a debugger and follow the value of `m_currentFrame` as you step through the program. You will surely find the problematic code section that way. –  Sep 10 '16 at 23:29

1 Answers1

0
if (m_currentFrame > frameCoordinates.size()){
    // Reset to the first frame.
    m_currentFrame = 0;

You already need to reset when m_currentFrame == frameCoordinates.size(), because the highest index of an array is its size minus one (counting begins at 0).

  • Worked! Thanks! Turns out the comment my lecturer had put in the framework for us to follow was incorrect, it said: "// W02.4: If the current frame is *greater* than the number of frames in this animation..." – ninja Sep 10 '16 at 23:39