Domanda

I have this function:

void getInput(vector<void*> &list)
{
    int qty, large;
    cout<<"How many random numbers do you wish to have? ";
    cin>>qty;
    cout<<"What is the largest number you wish to see? ";
    cin>>large;
    list.resize(qty+1);
    for(int i = 0; i < qty; i++)
    {
        int x = (rand()%(large+1));
        *((int*)list[i])=x;
    }
}

and it's crashing on the line

*((int*)list[i])=x;

in which I am stuck on how to fix. I am very new to this, and I've been searching books and websites...I only ask to be lead on the correct track. Thank you in advance!

È stato utile?

Soluzione

You shouldn't use a void* in the first place. You can use an std::vector<int> and have no problems at all:

void getInput(std::vector<int>& list)
{
    int qty, large;
    cout<<"How many random numbers do you wish to have? ";
    cin>>qty;
    cout<<"What is the largest number you wish to see? ";
    cin>>large;
    list.resize(qty);
    for(int i = 0; i < qty; i++)
    {
        list[i] = rand()%(large+1);
    }
}

But if you are interested, the reason why it was causing an error is because you were probably dereferencing an uninitialized pointer (if the values in the vectors were not initialized outside of the function).

And finally, if you have access to C++11, please consider dropping rand for uniformly generating random numbers.

Altri suggerimenti

Just like @Retired Ninja said, your pointers are pointing to nothing, causing a runtime error when you dereference them. You can either go with @Jefffrey's solution or you could use dynamic memory. Ex:

for (int i = 0; i < qty; i++)
{
    list[i] = new int; //now list[i] actually points to something
    int x = (rand() % (large + 1));
    *((int*) list[i]) = x;
}

Keep in mind that this approach is very dangerous and may cause a memory leak.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top