大家可以试试看,红框里第一个cout
运行输入数字会错误,而只保留第二个cout
的话输出是正确的?为什么这样,不是已经令他们相等了吗
另外附上源代码,这是输入几个数字在数组里,按字母结束输入。。开始运行按 1 2 q
就行。
#include <iostream>
using namespace std;
double* fill_array(double* begin);
void show_array(double* begin, double* end);
void reverse_array(double* begin, double* end);
const int N = 5;
int main()
{
double a[N], *end;
int n = 0;
cout << a << endl;
end = fill_array(a);
show_array(a, end);
reverse_array(a, end);
//show_array(a,end);
}
double* fill_array(double* begin)
{
double* ptr = begin;
int x;
while (cin >> x) {
*(ptr++) = x;
}
return ptr;
}
void show_array(double* begin, double* end)
{
double* ptr;
cout << "array:";
for (ptr = begin; ptr < end; ptr++)
cout << *ptr << " ";
cout << endl;
}
void reverse_array(double* begin, double* end)
{
double* ptr;
double* ptrb = ptr;
*ptr = *begin;
ptr++;
*ptr = *(end - 1);
double* ptre = ptr;
ptr = ptrb; //红框段
cout << *ptr << endl;
cout << *ptrb;
}
Just look at this piece of code. I will comment out anything irrelevant to
ptrb
firstHere comes the question:
The first sentence
ptr
is declared but not assigned, soptr
points to unknown;then
ptrb = ptr
, so at this timeptrb
also points to unknown; after,
ptr = ptrb; // 红框段
again Setptr
to point to an unknown address;Then... how could it not go wrong?
If you don’t seek death, you won’t die