我有这两个数组:
const char *face[] =
{"Deuce", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King", "Ace", "\0"};
const char *suit[] = { " of Hearts", " of Clubs", " of Diamonds", " of Spades", "\0" };
实际上,由于我在C++中的表现还不够好,所以我什至都不知道何时在数组中或其他地方使用星号。
但是无论如何,问题是我试图用这样的衣服打印出所有可能的卡片:
for (int n = 0; n<strlen(*suit); n++){ //where strlen(*suit) should be 4
for(int i = 0; i<strlen(*face); i++){ //where strlen(*face) should be 13
cout << endl << face[i] << suit[n] << endl;
}
}
使用该代码,我的程序崩溃了。我究竟做错了什么? (它在使用n
最佳答案
函数strlen
传递了const char*
,它是指向以null终止的字符数组的指针。您不能使用它来计算字符串数组的长度。
相反,我建议您这样做:
const char *face[] =
{"Deuce", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King", "Ace", NULL};
因此,前哨是空指针。像这样的循环:
for (int i=0; face[i]; i++)
// do something with face[i]
当然,对于其他数组也是如此。
现在,所有这些,对于C++程序来说,这是错误的方法。
std::string
代替使用C字符串,而是指向字符数组的指针。 std::vector<std::string>
。 我能给您的最好建议是忘记C的做事方式,并尝试学习惯用的C++编写代码的方式。
关于c++ - (C++)尝试打印出char *数组(我认为),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16002731/