【问题标题】:char* array keeps being set to nullptrchar* 数组一直设置为 nullptr
【发布时间】:2013-06-11 05:55:47
【问题描述】:

这是我的代码:

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

有人能解释一下到底发生了什么吗?

【问题讨论】:

  • delete []删除数组
  • 使用std::string 而不是char* 的麻烦会更少:cplusplus.com/reference/string/string/getline
  • 您的代码与问题不匹配:您在哪里打印“numEntries = ??” ?此外,您的 while 循环有问题 success 将根据数组中的最后一个字符设置,而不是整个设置。
  • 这段代码简直坏了。您分配了一个char 数组并将其存储在buffer 中,但随后您将buffer 移动到其他位置。稍后对其调用delete 只是未定义的行为(它应该是delete[],因为您分配了一个数组)。
  • @rajraj 在空指针上调用delete(或delete[])保证无操作,无需事先检查。

标签: c++ pointers getline atoi


【解决方案1】:

这是你的问题:

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

您可能想要做的是存储第二个指针,指向要与delete 一起使用的new [] 表达式的结果(也应该是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;
        }
    }
}

【讨论】:

  • 删除bufferptr如何删除缓冲区?
  • @Bbvarghe 因为您在将buffer 移走之前将bufferptr 设置为buffer。所以bufferptr 将指向需要删除的动态数组。另请参阅我对书籍的评论,直接在问题处。
  • 因此,这意味着 buffer = new char [MAX]' 没有将 buffer 设置为指针数组,其中每个索引指向字符串的不同字符,而是存储数组的指针保存字符串的字符数
  • @Bbvarghe 正是。而且由于您在第二个 while 循环期间移动了该指针,因此它不能用于删除操作。我提议的更改缓存了 new[] 返回的原始指针,然后将其传递给 delete[]。
猜你喜欢
  • 2017-09-05
  • 1970-01-01
  • 2021-08-08
  • 2018-01-23
  • 2011-08-20
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多