我有关于指针的问题。这是我的问题:
Write a function
int* read_data(int& size)
that reads data fromcin
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/