我还是比较新的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];
};
}
当我运行此程序时,它崩溃了,我不知道为什么。如果有人能帮助我弄清楚为什么会非常感激。谢谢。
答案 0 :(得分:2)
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;
}
答案 1 :(得分:1)
Array2[i + size]
无论i
的价值如何,您都可以访问越界。
你可能意味着Array2[size - 1 - i]
向后迭代数组。 (size - 1
是最后一个元素的索引。)
答案 2 :(得分:1)
通过使用交换,您将获得更好的解决方案,也更有效
void reverse(int *array, int size) {
for (int i = 0; i < size/2; i++) {
std::swap(array[i],array[size-1-i]);
};
}
答案 3 :(得分:0)
当您说int size = sizeof(Array) / 4;
时,size
现在是(5 * sizeof(int)) / 4
。这就是sizeof
运算符的工作方式(至少在应用于数组时)。
所以size
可能是5,假设是4字节int
。现在,您到达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];
}