无法在C ++中删除指针

时间:2019-03-16 03:41:33

标签: pointers visual-c++

我从一本书中获得了这段代码。当我在Visual Studio上运行时,它说将strcpy()切换到strcpy_s(),执行完之后,该程序似乎在删除指针处终止。我尝试在Dev-C ++上运行,并且工作正常。有人知道为什么吗?谢谢。

#include "pch.h"
#include <iostream>
#include <cstring>

int main()
{
    cout << "Enter a kind of animal: ";
    cin >> animal; // ok if input < 20 chars

    ps = animal; // set ps to point to string
    cout << ps << "!\n"; // ok, same as using animal
    cout << "Before using strcpy():\n";
    cout << animal << " at " << (int *)animal << endl;
    cout << ps << " at " << (int *)ps << endl;

    ps = new char[strlen(animal) + 1]; // get new storage
    strcpy_s(ps, sizeof(animal), animal); // copy string to new storage

    cout << "After using strcpy():\n";
    cout << animal << " at " << (int *)animal << endl;
    cout << ps << " at " << (int *)ps << endl;
    delete[] ps;
    return 0;
}

0 个答案:

没有答案