Reputation:
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;
}
Upvotes: 0
Views: 64
Reputation: 1833
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.
Upvotes: 0
Reputation: 96
#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;
}
Upvotes: 0
Reputation: 726479
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);
...
}
Upvotes: 2