0

I feel like an idiot. When I pass a variable to the function it results in a strange output like 6.2+e003 instead of the value that the variable holds. What am I doing wrong?

The x in main and the x in the function are different?

main:

int x, y;

while(system.WindowOpen())
{
    x++;
    y++;
    bg.Draw2D();
    bob.Think(x, y);
    riley.Think(x, y);
    system.Render(0);
}

class method:

void Organism::Think(double x, double y)
{
    std::cout << "X: " << x << "\n";
    std::vector<double> food;
    food.push_back(x);
    food.push_back(y);
    std::cout << "VECTOR: " << food[0] << " " << food[1] << "\n";
    std::vector<double> path;
    if(refresh.IsTime()) {
        std::cout << "\nFOOD VECTOR: \n" << food[0]
                  << "\n" << food[1] << "\n";

        path = brian.GetOutput(food);


        organism.Translate2D(path[0], path[1]);

        if(organism.IsOffScreen2D(resX, resY) == 'l' )
            organism.SetPos2D(resX, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 'r')
            organism.SetPos2D(0, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 't')
            organism.SetPos2D(organism.GetX(), resY);
        if(organism.IsOffScreen2D(resX, resY) == 'b')
            organism.SetPos2D(organism.GetX(), 0);
    };

    font.DrawNumber2D(x, 50, 50);
    font.DrawNumber2D(y, 50, 100);
    organism.Draw2D();
}
3
  • 3
    Is this the actual code because these variables are uninitialized which explains the random value.
    – Borgleader
    Jul 18, 2013 at 4:51
  • 6.2+e003 is 6200. And why are you passing integers to function that expect doubles? Also remember that x and y is not initialized, so you cannot predict what values they have Jul 18, 2013 at 6:23
  • X and Y where doubles initially, just trying other datatypes to see if it would fix the problem. Even the variables initialized, it still has the same problem.
    – Pearman
    Jul 19, 2013 at 3:07

2 Answers 2

4

Both x and y are uninitialized here:

int x, y;

so they can hold any value, and reading from them is undefined behaviour. You should initialize them:

int x = 0
int y = 0;
1
  • I did try that, still have the same problem.
    – Pearman
    Jul 18, 2013 at 20:05
0

I was writing outside the bounds of a vector. I switched from using the [] operators to using the .at() and found my bug right away. Just a bit of memory corruption. I feel quite silly. Thanks all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.