c# - c++指针见过最奇怪的情况
天蓬老师
天蓬老师 2017-04-17 14:47:58
0
2
292

大家可以试试看,红框里第一个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;
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
巴扎黑

Just look at this piece of code. I will comment out anything irrelevant to ptrb first

double *ptr;
double *ptrb=ptr;
//*ptr=*begin;
//ptr++;
//*ptr=*(end-1);
//double *ptre=ptr;

ptr=ptrb;    //红框段
cout<<*ptr<<endl;
cout<<*ptrb;

Here comes the question:

The first sentence ptr is declared but not assigned, so ptr points to unknown;
then ptrb = ptr, so at this time ptrb also points to unknown; after
, ptr = ptrb; // 红框段 again Set ptr to point to an unknown address;

Then... how could it not go wrong?

黄舟

If you don’t seek death, you won’t die

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template