创建新数组时写入位置时发生访问冲突

Access violation writing location on creation of new array

本文关键字:位置 访问冲突 创建 数组 新数组      更新时间:2023-10-16

我正在做家庭作业,班上的老师不允许我们提问。他要求我们试着自己解决这一切,但我在过去的一周里一直在努力让它发挥作用,但它也犯了同样的错误,我不知道为什么。我在谷歌上做了一些搜索,并浏览了SO,寻找任何有类似错误但找不到解决方案的人。

在创建新数组并输入用户输入开始填充新数组之后,它才能正常工作,然后抛出:

6b.exe中0x000B517B处的首次机会异常:0xC0000005:访问写入位置0x00008147的冲突。程序"[4112]6b.exe"已退出,代码为0(0x0)。

#include "stdafx.h"
#include <iostream>
using namespace std;
int* read_data(int& size){
size++;
return &size;   
}
void main(){
int size = 0; // size is 0 to start
int max = 10; // set max to 10 to start
float user; //user imputed float number
cout << "Start entering your numbers.n Be sure to hit RETURN between each one.nWhen you are finished, hit 'Q'n";
float *a = new float [max]; //set first array that can be deleted and replaced
do {
//if the array is full, make a new one and replace.
if(size == max){
max = max *2; //double max number
float *b = new float [max]; //create temporary array b
for (int i = 0; i < size; i++){
b[i] = a[i]; //copy old array to temporary
}
delete[] a; //remove old a array.
float *a = new float [max]; //create new a array with the new max, same name for the loop.
//copy new a array to resume filling
for(int i = 0; i< size; i++){
a[i] = b[i];
}
delete[] b; //remove temporary array to free memory.
}
cin >> user; // user inputs the number
a[size] = user; //user input
read_data(size); //increase size by one.
}while (!cin.fail());
size--; //remove one for the entering of Q otherwise it throws off the count.
if (cin.fail()){
cout << "nnYou have finished inputting.n You have imputed " << size << " numbers. nThe inputed numbers are as follows:n";
for(int i=0; i < size; i++){
cout << a[i];
if (i == size -1){
cout << "nn";
}
else {
cout << ", ";
}
}
cout << "nn";
}
system("pause"); 
}

教练希望基本上每一行都有评论,这就是为什么有这么多评论的原因。

如果有人能帮我,那就太好了。

delete[] a; //remove old a array.

这将删除您在main()函数的外部作用域中声明的a数组。

下一行:

float *a = new float [max]; 

这将在内部作用域中创建一个名为a的新变量。展望未来,你认为发生在你的原始a上的事情,在你的main()开始时声明的,实际上是对另一个a做的。原始的a是"隐藏的",因此,当这个范围结束时,您分配的新数组就会泄漏,而您的原始a数组现在指向未分配的内存。

Hillarity随之而来。

"你对管道的思考越多,就越容易停止排水"-斯科蒂,《星际迷航III》

在分配了新的b数组并将a的内容复制到它之后,您真正需要做的就是:

a=b;

您不需要分配另一个a数组,并将其从b复制回来,然后删除b。这样做毫无效果,而且你不经意间犯了一个相当邪恶的错误。。。