c++ - Array bug crashing the console -
i have no idea wrong here. problem array accessing last element contains terminating code. when use i <= sizeof(arr)
limiter in for
loop, 4 element list works, 3 element list crashes. if replace i < sizeof(arr)
, 3 element list works last element in 4 element list ignored.
int arraylist(string arr[]) { int choice; (unsigned int = 1; <= sizeof(arr); i++) { cout << << ". " << arr[i-1] << endl; } cout << "select number 1 " << sizeof(arr)-1 << ": "; cin >> choice; return choice; }
here function calls array list, crashes when fourth element accessed.
void titlescreen() { system("cls"); int choice = 0; { string arr[] = { "new game", "continue", "exit" }; choice = arraylist(arr); switch (choice) { case 1: newgame(); break; case 2: continuegame(); break; case 3: exitgame(); break; default: choice = 0; cout << "invalid choice." << endl; } } while (choice == 0); }
here segment calls list, works correctly.
do { string arr[] = { "attack", "guard", "skill", "item" }; switch (arraylist(arr)) { case 1: hero_act = hero->attack(foe); break; case 2: hero_act = hero->guard(); break; case 3: hero_act = hero->skill(foe); break; case 4: hero_act = hero->item(); break; default: cout << "action invalid." << endl; break; } } while (hero->hp > 0 && foe->hp > 0);
string arr[]; sizeof(arr);
is not want, since it's seen compiler as
string *arr; sizeof(arr);
this compile-time constant , return same value (the value depends on machine , compiler used) irrespective of how many elements in array.
passing in count parameter function (old c-style) option. however, if pass automatic arrays size known @ compile time, this
template <size_t n> int arraylist(string (&arr)[n]) { }
Comments
Post a Comment