grep
grep

Reputation: 4016

C++ vector issues

My application keeps crashing on me for whatever reason. I am new to vectors so there is more than likely something silly on my part.

#include <iostream>
#include <vector>    

using namespace std;

class Projectile
{
private:
    SDL_Surface *projectile;
    void load();

public:
    int count;

    vector< int > c;
    vector< vector< int > > p;

    int positionX;
    int positionY;

    Projectile();
    void newProjectile( int, int );
    void drawCurrentState( SDL_Surface* );
};

...
...

void Projectile::newProjectile( int x, int y )
{
    positionX = x;
    positionY = y;

    c.push_back( 10 );
    c.push_back( 10 );

    //p.push_back( c ); //trying to start off simple before i do multidimensional.
}

void Projectile::drawCurrentState( SDL_Surface* destination )
{   
    SDL_Rect offset;
    offset.x = c[0]; //will eventually me the multidimensional p vector
    offset.y = c[1]; //

    SDL_BlitSurface( projectile, NULL, destination, &offset );
}

what exactly am I doing wrong here? I push back two values ( will be the x and y ints after done testing ) however it seems to crash when it gets to the offset.x = c[0]; part of the script.

I thought for certain both c[0] and c[1] should be equal to 10. Any suggestions?

Upvotes: 0

Views: 192

Answers (3)

kadrian
kadrian

Reputation: 5009

The code seems to be okay, but the order of the calls is important. Make sure that you call newProjectile() before you call drawCurrentState(), for example like this:

Projectile * projectile = new Projectile();
projectile->newProjectile(1,1);
projectile->drawCurrentState( ... );

Upvotes: 2

Dialecticus
Dialecticus

Reputation: 16761

Maybe vector c is empty at line where c[0] is read. Check the result of c.size().

Upvotes: 1

brain
brain

Reputation: 2517

You're right, both [0] and [1] should be 10.

Just make sure you really call newProjectile() first, and make sure there are no other problems such as invalid destination pointer and so on.

Upvotes: 3

Related Questions