char *数组保持设置为nullptr

时间:2013-06-11 05:55:47

标签: c++ pointers getline atoi

这是我的代码:

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”,如果输入字符串,它会崩溃。

有人可以解释究竟发生了什么吗?

1 个答案:

答案 0 :(得分: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;
        }
    }
}