简体   繁体   English

如何初始化2D字符数组

[英]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? 为什么不能像这样初始化2D数组?

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

It compiles without errors and warnings, but cout << alphab[0][5] prints nothing. 它编译时没有错误和警告,但是cout << alphab[0][5]打印任何内容。

  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. 答案为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. 因为您没有2D的指针到字符数组,而只有1D的指针到字符数组。 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. 答案为2。

Count the number of characters and add an extra one for the \\0 character. 计算字符数,并为\\0字符添加一个额外的字符。 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和char *。 char* can make an array of chars it self! char *可以自己创建一个char数组! leave an extra unit for \\n. 为\\ n保留一个额外的单位。

You can now easily reference the alphab. 现在,您可以轻松引用alphab。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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