0

What I'm trying to output is the dealer's roll (the numbers are supposed to be stored in an array) but I keep getting an error that int is an invalid type in DealerRoll(dealerRoll[3]);

#include <iostream>
#include <time.h>
#include <stdio.h>      
#include <stdlib.h>  
using namespace std;

//Dice Rolls
int DealerRoll(int dealerRoll[3]) {
    srand (time(NULL));
    for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
        dealerRoll[dealerCount] = rand()% 6+1;
        cout << dealerRoll[dealerCount] << " ";
    }
    return dealerRoll[3];
}

int main() {
    int dealerRoll;
    cout << "Dealer's Roll: " << endl;
    DealerRoll(dealerRoll[3]);
    system ("pause");
    return 0;
}
1
  • return dealerRoll[3]; is returning an int that is outside the array, The largest indexed element in dealerRoll is dealerRoll[2] Commented Apr 8, 2017 at 3:47

3 Answers 3

2

Although you can make an array in a function, std::vector provides better flexibility, and deals with resource management for you.

If array size is fixed, you can use std::array<int,3> instead:

void DealerRoll(std::array<int,3>& dealerRoll) {
    srand (time(NULL));
    for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
        dealerRoll[dealerCount] = rand()% 6+1;
        cout << dealerRoll[dealerCount] << " ";
    }
}
...
int main() {
    std::array<int,3> dealerRoll;
    cout << "Dealer's Roll: " << endl;
    DealerRoll(dealerRoll);
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change the line int dealerRoll; as int dealerRoll[3];

Reason: You need to pass the array to function but you are declaring the integer variable.

Change the line DealerRoll(dealerRoll[3]); as DealerRoll(dealerRoll);

Reason: Function takes array as input but you have passed the 3rd position of array(Which will decompose to integer) instead of array.

Comments

0
#include <iostream>
#include <time.h>
#include <stdio.h>      
#include <stdlib.h>  
using namespace std;

//Dice Rolls
void DealerRoll(int* dealerRoll)   //retrieving array in pointer
{
    srand (time(NULL));
    for (int dealerCount = 0; dealerCount < 3; dealerCount++)
    {
    dealerRoll[dealerCount] = rand()% 6+1;
    cout << dealerRoll[dealerCount] << " ";
    }

}

int main()
{
    int dealerRoll[3];    //syntax for creating array

    cout << "Dealer's Roll: " << endl;
    DealerRoll(dealerRoll);  //passing address of array in function

    //As Values are passed by address, values retained in array
    cout<<"\nValues in Dealer's Roll : "<<endl;
    for (int dealerCount = 0; dealerCount < 3; dealerCount++)
    {
        cout << dealerRoll[dealerCount] << " "; 
    }
system ("pause");
return 0;
}

Comments

Your Answer

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