教授在C++中“新”的例子在我的机器上不起作用

Professors example of `new` in C++ will not work on my machine

本文关键字:我的 不起作用 机器 C++      更新时间:2023-10-16

这是教授的代码:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
#include <new>
int main()
{
    char *p;
    int index = 8;
    cout << "Input how many characters:";
    cin >> index;
    p = new char [index + 1];
    cin >> p;
    cout << "p is: " << p;
    delete [] p;
    p = NULL;
    return 0;
}

在我数字回答"多少个字符"语句后,程序停止。

有人知道为什么吗?

首先你有

cin >> index;

您必须在其中输入字符数。

然后你有

cin >> p;

您必须输入一些字符 - 但不超过您之前给出的数字。你在这样做吗?给出另一个提示可能会有所帮助:

cout << "Input up to " << index << " characters:";
cin >> p;

我希望您的教授能够跟进对缓冲区溢出、输入验证、异常安全以及如何使用std::string来避免手动分配的失误。否则,你就会被教导一些非常坏的习惯。