[英]Deallocating Dynamic Memory
我最近做了一次學校作業,但丟了分數。在評論中,該校生說我沒有正確分配指針。 以下是我發送的代碼,我想知道如何正確地釋放指針?
/*Student: Daniel
*Purpose: To reverse a string input using
*pointers.
*/
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string input;
char *head = new char, *tail = new char;
char temp;
//Get the string from the user that will be reversed
cout << "Enter in a string that you want reversed: ";
getline(cin, input);
//Create and copy the string into a character array
char arr[input.length()];
strcpy(arr, input.c_str());
//Set the points of head/tail to the front/back of array, respectably
head = &arr[0]; tail = &arr[input.length()-1];
for(int i=0; i<input.length()/2; i++) {
temp = *(tail);
*tail = *head;
*head = temp;
tail --; head ++;
}
for(int i=0; i<input.length(); i++) {
cout << arr[i];
}
//********MY PROBLEM AREA*************
delete head; delete tail;
head = NULL; tail = NULL;
return 0;
}
所以在這里看看...
char *head = new char, *tail = new char;
接着...
//Set the points of head/tail to the front/back of array, respectably
head = &arr[0]; tail = &arr[input.length()-1];
您重新分配什么head
和tail
點,這樣你就不會真正刪除正確的事情,當你調用刪除。 實際上,我很驚訝您沒有崩潰。
確實可以做到:
char *head = NULL; char* tail = NULL;
然后不要刪除任何內容,因為您將沒有動態內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.