c# - c++指针见过最奇怪的情况

浏览:36日期:2023-04-11

问题描述

c# - c++指针见过最奇怪的情况

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

问题解答

回答1:

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

double *ptr;double *ptrb=ptr;//*ptr=*begin;//ptr++;//*ptr=*(end-1);//double *ptre=ptr;ptr=ptrb; //红框段cout<<*ptr<<endl;cout<<*ptrb;

问题来了:

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

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

回答2:

不作死就不会死

相关文章: