![](/img/trans.png)
[英]Access violation writing location 0x00000000. memset function issues
[英]Access violation writing location 0x00000000. problems with pointers
我在分配某些代碼時遇到麻煩。 該程序基於面向大學生的在線競賽問題存檔。
這是頭文件:
#include <iostream>
#include <cmath>
using namespace std;
class Vito
{
public:
Vito(int relative_count); //constructor
~Vito(); //destructor
int min(); //finds minimum "distance" between vito's relatives
private:
int *streets; //pointer to array of street numbers
int sum(int index); //generates sum of distances for each of vito's relatives
void getStreetNums(); //retrieves street numbers from user
int relatives; //used globaly to set number of repititions
};
Vito::Vito(int relative_count = 0)
{
int *streets = new int[relative_count]; //allocates memory for array streets
relatives = relative_count;
getStreetNums();
}
Vito::~Vito()
{ delete [] streets; } //releases memory used by class
void Vito::getStreetNums()
{
cout << "Enter all street numbers, seperated by a space: ";
int street_num;
for (int i = 0; i < relatives; i++)
{
cin >> street_num;
streets[i] = street_num;
}
}
int Vito::min()
{
int MIN = 65546, test_distance; //initialized to maximum possible value for an integer in C++
for (int i = 0; i < relatives; i++)
{
test_distance = sum(i);
if( MIN > test_distance )
{ MIN = test_distance; }
}
return MIN;
}
int Vito::sum(int index)
{
int SUM = 0, street_num;
street_num = *(streets+index); //set value for determining distances between one house and the others
for (int i = 0; i < relatives; i++)
{ SUM += abs( street_num - streets[i] ); }
return SUM;
}
這是主要的:
#include <iostream>
#include "proj_02.h"
using namespace std;
int main()
{
int relatives, tests;
cout << "This program will supply a minimum distance between homes based on a given number of relatives and street numbers their homes are on. All entered values must be integers." << endl << endl;
cout << "Enter how many tests will be run: ";
cin >> tests;
for (int i = 0; i < tests; i++)
{
cout << "Enter how many relatives will be used in test " << i+1 << ": ";
cin >> relatives;
Vito family(relatives);
cout << "For this case, the minimum distance between each relatives house compared to each other is: " << family.min() << endl << endl;
}
}
執行后,我收到一條錯誤消息,內容為“ 0xC0000005:訪問沖突寫入位置0x00000000”。 這里:
void Vito::getStreetNums()
{
cout << "Enter all street numbers, seperated by a space: ";
int street_num;
for (int i = 0; i < relatives; i++)
{
cin >> street_num;
streets[i] = street_num;
}
}
調試顯示為街道設置了空的內存地址,但是我在構造函數中為它分配了內存。 誰能解釋這是怎么回事?
Vito::Vito(int relative_count = 0)
{
int *streets = new int[relative_count]; //allocates memory for array streets
在構造函數中,您定義了一個局部變量streets
,並為其分配內存。 局部可變的streets
遮蓋了班級成員的streets
。 更改為:
Vito::Vito(int relative_count = 0)
{
streets = new int[relative_count]; //allocates memory for array streets
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.