2016-12-17 87 views
0

我已收到異常過程中「引發的異常」是接收回路

Exception thrown at 0x70F8516F (vcruntime140d.dll) in Project.exe: 0xC0000005: Access violation writing location 0x723D9C18. 

它的用戶定義的信息的最終迭代到一個數組中時的for循環發生:

int k; 
cout << "Enter array size:"; 
cin >> k; 
while (k > 3) { 

    cout << "Array size too big, please reenter" << endl; 
    cin >> k; 

} 

Player *ptr = new Player[k]; 

string n; 
int s; 

for (int i = 0; k >= i; i++) { 

    cout << "Enter name" << endl; 
    cin >> n; 
    ptr[i].setName(n); 

    cout << "Enter score" << endl; 
    cin >> s; 
    ptr[i].setScore(s); 

    ptr[i].getName(); 
    ptr[i].getScore(); 

} 

而它引導我到我的setName函數的末尾

void Player::setName(string n) { 

    name = n; 

} 
+0

緩衝區溢出。當循環中的「i == k」時會發生什麼? – PaulMcKenzie

+0

在循環中,如果第一次迭代值爲零,則結束條件通常爲'<' (or '>'),而不是'<=' or '> ='。 – Dialecticus

+1

只需在for循環中用'k> i'替換'k> = i'。經典的方法是使用'我 alexolut

回答

0

你應該寫

Player *ptr = new Player[k+1]; 

假設您的值k爲5,那麼您的循環將迭代6次(0到5),並且您僅爲5個對象分配了空間。這就是爲什麼它會拋出異常。

+1

你爲什麼認爲'Player'需要再聲明一次呢?如果循環條件錯誤怎麼辦? – PaulMcKenzie

+0

@PaulMcKenzie,請仔細看看代碼。 –

+0

@PaulMcKenzie但是...這將防止異常:)以及任何其他正位N:'新球員[K + N]'哈哈... – alexolut

1

您的陣列大小應爲(K + 1)或for循環應該是這樣的:

for (int i = 0; i<k; i++) { 

cout << "Enter name" << endl; 
cin >> n; 
ptr[i].setName(n); 

cout << "Enter score" << endl; 
cin >> s; 
ptr[i].setScore(s); 

ptr[i].getName(); 
ptr[i].getScore(); 

}