c++指针见过最奇怪的情况
高洛峰
高洛峰 2016-11-12 10:18:32
0
1
692

3513635114-57f0a2e741d7c_articlex.png

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


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
三叔

就看这一段代码,我把与 ptrb 无关的先注释掉

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

ptr=ptrb;    //红框段
cout

问题来了:

第一句 ptr 申明了但未赋值,所以 ptr 的指向未知; 
然后 ptrb = ptr,所以这时候 ptrb 也指向未知; 
后面 ptr = ptrb; // 红框段,又把 ptr 置为指向未知地址的境地;

然后……怎么可能会不出错呢?


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!