c++ - How to initialize 2D array of chars -
c++ - How to initialize 2D array of chars -
i trying write simple name generator, got stuck array initialization.
why can't initialize 2d array this?
const char* alphab[2][26] ={{"abcdefghijklmnopqrstuvwxyz"}, {"abcdefghijklmnopqrstuvwxyz"}};
it compiles without errors , warnings, cout << alphab[0][5]
prints nothing.
why this
class sample{ private: char alphnum[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; }
throw "initializer-string array of chars long" error, , this
char alphnum[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; class sample{ //code };
doesn't?
here code
class namegen { private: string str; char arr[5]; const char* alphab[2][26] = {{"abcdefghijklmnopqrstuvwxyz"}, {"abcdefghijklmnopqrstuvwxyz"} }; public: string genname() { srand(time(0)); (unsigned int = 0; < sizeof(arr); ++i) { arr[i] = *alphab[(i > 0) ? 1 : 0][rand() % 25]; } str = arr; homecoming str; } } alph; int main() { cout << alph.genname() << endl; homecoming 0; }
no warnings , errors. output is: segmentation fault (code dumped)
the reply 1.
const char* alphab[2][26] ={{"abcdefghijklmnopqrstuvwxyz"}, {"abcdefghijklmnopqrstuvwxyz"}};
should
const char* alphab[2] ={{"abcdefghijklmnopqrstuvwxyz"}, {"abcdefghijklmnopqrstuvwxyz"}};
since don't have 2-d array of pointer-to-char 1-d array of pointer-to-chars. line
arr[i] = *alphab[(i>0) ? 1: 0][rand() % 25];
should changed
arr[i] = alphab[(i>0) ? 1: 0][rand() % 25];
live illustration here.
the reply 2.
count number of characters , add together 1 \0
character. cannot have zero-sized array fellow member variable, must specify length,
char alphnum[5] = "test";
c++ arrays
Comments
Post a Comment