【发布时间】:2020-07-19 01:20:07
【问题描述】:
我需要编写一个 C++ 程序,它在两个 1 维之间交换 使用指针和函数的数组。首先,一个名为 showValues 的 void 函数在交换之前显示两个数组,还有一个名为 swap 的 void 函数来交换两个数组之间的元素。
我的问题是:我应该交换函数,但由于某种原因它无法运行,我不确定代码中的错误在哪里
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 5;
void showValues(int[],int[]);
void swap(int[],int[]);
int main() {
int array1[SIZE] = {10,20,30,40,50};
int array2[SIZE] = {60,70,80,90,100};
showValues (array1, array2);
swap(array1, array2);
return 0;
}
void showValues(int array1[], int array2[]){
cout<<"The original arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
void swap(int array1[], int array2[])
{
int temp,i;
for(i=0; i<5; ++i)
{
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
}
cout << "\nThe swapped arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
【问题讨论】:
-
你好像忘了问问题。
-
在
swap()函数中,temp = array1[SIZE];语句并没有按照您的想法执行。接下来的两个陈述也没有。他们都没有做你认为他们做的事。 -
我应该交换函数,但由于某种原因它无法运行,我不确定代码中的错误在哪里
-
下次在调试器中单步调试代码会非常有用。然后你会注意到
temp包含一个垃圾值,在调查为什么会这样时你会注意到SIZE等于5,因此你正在访问超出数组末尾的array1[5](如它的最后一个元素是array1[4])。 -
不要调用你的函数
swap,同时有using namespace std;。您的代码很有可能会调用std::swap而不是您自己的版本。
标签: c++ arrays function pointers