[英]C++ Program crashing when trying to add values to an array (or a vector) inside a class
[英]C++ Program crashing when trying to rearrange array
我對C ++還是比較陌生。 我正在嘗試編寫一個程序,該程序接受一個數字數組,並使用一個函數反轉這些數字在數組中的順序。 該程序如下:
#include <iostream>
using namespace std;
void reverse(int *array, int size);
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / 4;
reverse(Array, size);
return 0;
}
void reverse(int *array, int size) {
int Array2[5];
for (int i = 0; i < size; i++) {
Array2[i + size] = array[i];
array[i + size] = Array2[i + size];
};
}
當我運行該程序時,它崩潰了,我不確定為什么。 如果有人可以幫助我弄清楚為什么,將不勝感激。 謝謝。
真力時(Zenith)擁有它,但是這里有一些要點和快速技巧可以幫助您。
#include <iostream>
//using namespace std; don't need this, and using namespace std is overkill and often
// causes problems. It pulls in a lot of stuff that may conflict, case in point
// std::reverse now becomes reverse. Which reverse will you get? Your reverse or the standard
// library's reverse? Only pull in what you need, for example
using std::cout; // still not used, but makes a good example.
void reverse(int *array, int size)
{
// no need for the other array and another loop. You can swap each element for
//it's counterpart in the upper half of the array.
for (int i = 0; i < size /2 ; i++) // only need to go half way. Other half was
// already swapped doing the first half.
{
int temp = array[i]; // store a temporary copy of element i
array[i] = array[size-1-i]; // replace element i with it's counterpart
// from the second half of the array
array[size-1-i] = temp; // replace the counterpart of i with the copy of i
// or call std::swap(array[i], array[size-1-i]);
};
}
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
// int size = sizeof(Array) / 4; using 4 here can trip you up on a computer with
// a different sized int
int size = sizeof(Array) / sizeof(Array[0]);
// dividing the size of the array by the size of an element in the array will always
// get you the correct size
reverse(Array, size);
return 0;
}
Array2[i + size]
無論i
的值是多少,您都在訪問邊界。
您可能是說Array2[size - 1 - i]
向后迭代數組。 ( size - 1
是最后一個元素的索引。)
通過使用交換,您將獲得更好的解決方案,並且效率更高
void reverse(int *array, int size) {
for (int i = 0; i < size/2; i++) {
std::swap(array[i],array[size-1-i]);
};
}
當你說int size = sizeof(Array) / 4;
, size
現在為(5 * sizeof(int)) / 4
。 這就是sizeof
運算符的工作方式(至少在應用於數組時)。
因此,假設int
為4字節,則size
可能為5。 現在,您可以reverse
,其參數size
也為5。
您進入了for
循環,甚至在第一次迭代時,您都有Array2[5] = /* something */
和array[5] = /* something */
,它們都是緩沖區溢出。
另外,您的reverse
功能實際上不會進行任何反向操作。 嘗試這個:
void reverse(int *arr, int size);
int main()
{
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / sizeof(int);
reverse(Array, size);
return 0;
}
void reverse(int *arr, int size)
{
int temp[5];
for (int i = 0; i < size; i++)
temp[size - 1 - i] = arr[i];
for (int i = 0; i < size; i++)
arr[i] = temp[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.