NotSoCasualGamer
NotSoCasualGamer

Reputation: 43

Pointer returning from another class

Alright so in Class A I have:

int* attackerDice;
int* defenderDice;

these two variables call on another class called dice. So:

attackerDice = dice.roll()
defenderDice = dice.roll()

what dice.roll does is the following:

int* Dice::roll () {
    int* ran = new int[1];
    srand(time(NULL));
    ran[0] = rand()%6+1;
    std::sort(ran,ran+1);
    return ran; 
}

Now the problem that I am getting is attackerDice is returning -43249211234 while defender dice is returning the right number. I assume this is because I clearly do not understand when to use * and &. Can anyone help me out?

Edit: How would I go about doing this if I wanted to have an array? Id like to have it so that I can roll X number of dice

Upvotes: 2

Views: 78

Answers (2)

Shoe
Shoe

Reputation: 76240

Pretty much everything about your code is suboptimal:

  • You are using dynamic allocation when there's really no need.
  • You are allocating an array of a single element and sorting it (which makes no sense by the way).
  • You are using rand which has been considered "evil" for quite some time now.
  • You are putting an algorithm that does not use any member object of the class Dice as one of its member functions.

A revised "sane" solution would be the following:

namespace ex {
    class dice {
    private:
        std::mt19937 gen;
        std::uniform_int_distribution<> dis;
    public:
        dice(int to)
            : gen(std::random_device()())
            , dis(1, to)
            {}

        int roll() { return dis(gen); }
    };
}

which would then be used as something like:

constexpr int count = 10;
std::vector<int> rolls;
rolls.reserve(count);

ex::dice dice(6);
std::generate_n(back_inserter(rolls), count, std::bind(&ex::dice::roll, dice));

Live demo

Upvotes: 2

sehe
sehe

Reputation: 393064

My crystal ball says that Dice doesn't obey Rule Of Three.

It looks like you're having Undefined Behaviour because of mismanaged pointers and the lifetime of the objects they are pointing to.

In most cases, C++ doesn't require the use of pointers anyways.

Don't Write new In C++

See Jeffrey's answer for an idea how to avoid the lifetime issues.

Much better. Caution: It's very suboptimal to instantiate a new random generator each time through the loop, and using a uniform distribution like that is flawed. Instead, do:

auto dice = bind(uniform_int_distribution<>(1,6), mt19337 { random_device{}() });

Now you can just call

int roll1 = dice(); // roll1 = [1..6]

And it will actually be uniformly distributed as long as you use the same dice object

Upvotes: 3

Related Questions