c++ - C++中的堆和指针

标签 c++ arrays pointers heap-memory

我有关于指针的问题。这是我的问题:

Write a function int* read_data(int& size) that reads data from cin until the user terminates input by entering Q. The function should set the size reference parameter to the number of numeric inputs. Return a pointer to an array on the heap. That array should have exactly size elements. Of course, you won’t know at the outset how many elements the user will enter. Start with an array of 10 elements, and double the size whenever the array fills up. At the end, allocate an array of the correct size and copy all the inputs into it. Be sure to delete any intermediate arrays.

这是我的代码:

int* read_data(int& size);
int main()
{
    int size ;
    int* account_pointer = read_data(size);
    int* account_array = new int[size];

    int* bigger_array = new int[2 * size];
    for (int i = 0; i < size; i++)
    {
        bigger_array[i] = account_array[i];
    }
    delete[] account_array;
    account_array = bigger_array;
    size = 2 * size;

    system("PAUSE");
    return 0;
}

int* read_data(int& size)
{
    int input;
    cout << "Enter integer, Q to quit : " ;
    while(cin >> input)
    {
        size++;
    }
    return &size;
}

但是,当我插入非数字时,我收到一条错误消息。错误消息是 Debug Error!分配大小无效:4294967295 字节。我在 main 方法中错误地声明了 size 变量吗?还是我的整个代码编码错误?

最佳答案

main()中需要将size初始化为0,如果没有初始化,它的值是undefined。

关于c++ - C++中的堆和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16523603/

相关文章:

c++ - 我怎么知道我是否需要删除 C++ 中的某些内容?

具有可变参数的 C++ 模板函数

c++ - 如何为 string_view 创建 (VC14) 调试可视化工具?

C#。通过电子邮件发送 byte[] 然后检索它

javascript - 使用三元运算符进行数组解构

python - 在python中找到两个二维数组之间的区别

C:结构是作为指针实现的吗?

c - 是否允许编译器回收释放的指针变量?

c++ - 如何使用带有 future<T> vector 的基于范围的 for 循环

C++/Qt 与 Adob​​e AIR