-1

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!

yizzlez
  • 8,757
  • 4
  • 29
  • 44
Jordan Huang
  • 25
  • 1
  • 8
  • 2
    Why does it contain `void *` in the first place? It should probably just be a `std::vector`. – chris Apr 15 '14 at 21:46
  • 1
    You have pointers in your vector but they point to nothing. – Retired Ninja Apr 15 '14 at 21:47
  • @chris That doesn't help. Even if it is in `vector`, it's still going to crash. – Jordan Huang Apr 15 '14 at 21:50
  • @SamHuang, Well, I meant not to cast it at all with using that, but it seems you're not allowed to do that for some reason. – chris Apr 15 '14 at 21:57
  • @SamHuang: If you have a `vector` (as you should here) then you have no pointers at all, you will just `push` new elements `_back`. No crash, proper code. – Ed S. Apr 15 '14 at 22:06

2 Answers2

2

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.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
0

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.

yizzlez
  • 8,757
  • 4
  • 29
  • 44