+ 1

getting segmentation fault sometimes

#include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(static_cast <unsigned int> (time(0))); int numchoices; cout<<"How many things is there to pick from?\n"; cin>>(numchoices); if(numchoices < 1) { cout<<"Error: Cannot allocate null number of choices;\nClosing program...\n"; return 0; } cout<<"\n alright then enter the "<<(numchoices)<<" things.\n"; string choices[(numchoices)-1]; for(int x = 0;x<numchoices;x++) { cout<<":"<<x+1<<" "; cin>>choices[x]; } cout<<"Alright i have picked;\n"; int pick = (rand() % numchoices-1) +1; cout<<pick<<": "; cout<<choices[pick-1]<<endl; return 0; }

21st Aug 2016, 11:22 PM
Null Void
Null Void - avatar
8 ответов
+ 1
You allocate numchoices-1 choices but use numchoices.
22nd Aug 2016, 12:02 AM
Stefan
Stefan - avatar
+ 1
Oh whoops my bad, thanks Stefan
22nd Aug 2016, 12:04 AM
Null Void
Null Void - avatar
+ 1
Also your calculation for pick is a bit confusing. Just do rand() % numchoices
22nd Aug 2016, 12:04 AM
Stefan
Stefan - avatar
+ 1
No prob :-)
22nd Aug 2016, 12:04 AM
Stefan
Stefan - avatar
+ 1
I usually account for number guesses being 1-10 rather than 0-9 due to arrays, made a mistake
22nd Aug 2016, 12:08 AM
Null Void
Null Void - avatar
+ 1
thanks for the help
22nd Aug 2016, 12:08 AM
Null Void
Null Void - avatar
+ 1
No prob @ all 😎
22nd Aug 2016, 1:02 AM
Stefan
Stefan - avatar
+ 1
;)
22nd Aug 2016, 1:04 AM
Null Void
Null Void - avatar