-4

这是我的代码:

int main () 

{
    const int MAX = 10;
    char *buffer = nullptr;       // used to get input to initialize numEntries
    int ARRAY_SIZE = 20;            // default is 20 entries

    int numEntries;
    success = false;

    while (!success)
    {
        delete buffer;
        buffer = nullptr;
        buffer =  new char [MAX];

        cout << "How many data entries:\t";
        cin.getline(buffer, MAX, '\n');

        cout << endl << endl;

        while (*buffer)
        {
            if (isdigit(*buffer++))
                success = true;
            else
        {       
               success = false;
                break;
        }
    }
}

numEntries = atoi(buffer);

问题是当我输入一个任意数字时,它只显示“numEntries = 0”,如果我输入一个字符串,它就会崩溃。

有人可以解释到底发生了什么吗?

4

1 回答 1

0

这是你的问题:

+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
  ^                         ^
  |                         |
 Start                     End
  • Start是从new []表达式返回的指针。
  • 第二个 while 循环while (*buffer)迭代地将指针移动到由 表示的位置End
  • End传递给delete. 这是错误的。 Start想要传递给delete.

您可能想要做的是存储第二个指针,该指针指向要new []使用的表达式的结果delete(也应该是delete []) 例如:

int main () 
{
    const int MAX = 10;
    char *buffer = nullptr;       // used to get input to initialize numEntries
    char *bufferptr = nullptr;    // <- ADDED
    int ARRAY_SIZE = 20;            // default is 20 entries

    int index = 0;
    success = false;

    while (!success)
    {
        delete [] bufferptr; // <- CHANGED
        buffer = nullptr;
        buffer =  new char [MAX];
        bufferptr = buffer; // <- ADDED

        cout << "How many data entries:\t";
        cin.getline(buffer, MAX, '\n');

        cout << endl << endl;

        while (*buffer)
        {
            if (isdigit(*buffer++))
                success = true;
            else
                success = false;
        }
    }
}
于 2013-06-11T06:57:01.437 回答