很久以前我在读一本书,并告诉我如何为指针分配和释放内存的模式。出于某种原因,它现在不适用于我的项目和我之前的项目。直到现在我才决定解决这个分配问题。所以这是有问题的代码:
// Encrypting or Decrypting Mode
bool ModeSelected(false); // stores the result if the user had selected a valid mode
bool Mode(ENCRYPT); // saves the Mode if Encrypt or Decrypt
while(!ModeSelected)
{
cout << "Enter E to Encrypt or D to Decrypt: " << endl;
char resultED[MAXCHAR]; // stores the result if to Encrypt or Decrypt
char *presultED(nullptr); // stores the result
cin.getline(resultED, MAXCHAR, '\n');
presultED = new char((strlen(resultED)) + 1);
strcpy(presultED, resultED); // copy the result the char pointer variable
if((*(presultED + 0) == 'E') ||
(*(presultED + 0) == 'e')) // The user wants Encrypt
{
cout << endl << "Encrypt Mode is Selected" << endl;
Mode = ENCRYPT;
ModeSelected = true;
}
else if ((*(presultED + 0) == 'D') ||
(*(presultED + 0) == 'd')) // The user wants Decrypt
{
cout << endl << "Decrypt Mode is Selected" << endl;
Mode = DECRYPT;
ModeSelected = true;
}
else
{
// Input is invalid
cout << endl << "Input is invalid" << endl;
}
// clean up
if(presultED) // If not null then delete it
{
// Garbage collection
// Contact Stack Overflow
delete[] presultED;
presultED = nullptr;
}
}
您会看到代码的// clean up部分正是这本书告诉我如何释放内存的。我也有点了解这背后的计算机科学。现在请告诉我这个问题。谢谢你。