简体   繁体   中英

How to initialize 2D array of chars

I was trying to write a simple name generator, but I got stuck with array initialization.

  1. Why can't I initialize 2D array like this?

     const char* alphab[2][26] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}, {"abcdefghijklmnopqrstuvwxyz"}}; 

It compiles without errors and warnings, but cout << alphab[0][5] prints nothing.

  1. Why does this

     class Sample{ private: char alphnum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; } 

throw an "initializer-string for array of chars is too long" error, and this

char alphnum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
class Sample{
//code
};

doesn't?

Here is my code

class NameGen {

private:
    string str;
    char arr[5];
    const char* alphab[2][26] = {{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
        {"abcdefghijklmnopqrstuvwxyz"}
    };

public:
    string genName()
    {
        srand(time(0));
        for (unsigned int i = 0; i < sizeof(arr); ++i) {
            arr[i] = *alphab[(i > 0) ? 1 : 0][rand() % 25];
        }
        str = arr;
        return str;
    }
} alph;

int main()
{
    cout << alph.genName() << endl;
    return 0;
}

No warnings and errors. The output is: Segmentation fault (code dumped)

The answer to 1.

const char* alphab[2][26] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
                            {"abcdefghijklmnopqrstuvwxyz"}};

should be

const char* alphab[2] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
                        {"abcdefghijklmnopqrstuvwxyz"}};

since you don't have an 2-D array of pointer-to-char but just a 1-D array of pointer-to-chars. The line

arr[i] = *alphab[(i>0) ? 1: 0][rand() % 25];

should then be changed to

arr[i] = alphab[(i>0) ? 1: 0][rand() % 25];

Live example here .

The answer to 2.

Count the number of characters and add an extra one for the \\0 character. You cannot have a zero-sized array as a member variable, so must specify the length, like

char alphnum[5] = "test";

Try this one:

char alphab[2][27] = { 
    {"abcdefghijklmnopqrstuvwxyz"}, 
    {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
};

Notice the use of char and char* . char* can make an array of chars it self! leave an extra unit for \\n.

You can now easily reference the alphab.

Cout<< alphab[1][5] ;    //you will get 'F'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM