嘿伙计们,我正在尝试练习C++,而在这样做时我遇到了代码中的问题.我动态创建一个字符数组,然后对于每个数组索引,我想用一个整数填充该元素.我尝试将整数转换为字符,但这似乎不起作用.打印出数组元素后,什么都没有出来.我很感激任何帮助,我对此很新,谢谢.
char *createBoard()
{
char *theGameBoard = new char[8];
for (int i = 0; i < 8; i++)
theGameBoard[i] = (char)i; //doesn't work
return theGameBoard;
}
Run Code Online (Sandbox Code Playgroud)
以下是我最终如何做到这一点.
char *createBoard()
{
char *theGameBoard = new char[8];
theGameBoard[0] = '0';
theGameBoard[1] = '1';
theGameBoard[2] = '2';
theGameBoard[3] = '3';
theGameBoard[4] = '4';
theGameBoard[5] = '5';
theGameBoard[6] = '6';
theGameBoard[7] = '7';
theGameBoard[8] = '8';
return theGameBoard;
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*scu 15
基本上,你的两段代码并不完全相同.
当您设置GameBoard [0] ='0'时,您实际上将其设置为值48(字符'0'的ASCII代码).因此,如果i = 0,设置GameBoard [0] =(char)i并不完全相同.您需要在ASCII表(即48)中添加'0'的偏移量,以便theGameBoard [0]实际上是0 +字符'0'的偏移量.
这是你如何做到的:
char *createBoard()
{
char *theGameBoard = new char[8];
for (int i = 0; i < 8; i++)
theGameBoard[i] = '0' + (char)i; //you want to set each array cell
// to an ASCII numnber (so use '0' as an offset)
return theGameBoard;
}
Run Code Online (Sandbox Code Playgroud)
另外,像@Daniel所说的那样:确保在完成使用返回的变量后,释放你在此函数中分配的内存.像这样:
int main()
{
char* gameBoard = createBoard();
// you can now use the gameBoard variable here
// ...
// when you are done with it
// make sure to call delete on it
delete[] gameBoard;
// exit the program here..
return 0;
}
Run Code Online (Sandbox Code Playgroud)