1

私は最近、学校の宿題をしてポイントを失いました。採点者のコメントで、ポインターの割り当てを正しく解除しなかったとのことでした。以下は私が送信したコードです。ポインターの割り当てを正しく解除するとどうなるか知りたいですか?

/*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;
}
4

1 に答える 1

7

では、こちらをご覧ください...

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];

whatheadtailpoint を再割り当てしたため、delete を呼び出したときに実際には正しいものを削除していません。実際、あなたがクラッシュしないことに驚いています。

実際には、おそらく次のことができます。

char *head = NULL; char* tail = NULL;

動的なものがないため、何も削除しないでください。

于 2013-11-10T02:28:24.453 に答える