【发布时间】:2015-05-24 23:51:18
【问题描述】:
代码按预期工作,直到第 22-24 行,我们打印 8 后跟地址。增加指针地址只会将地址增加一个字节,而它应该将地址移动 4 个字节。数组中或单独运行第 22-24 行时不会出现此问题。
#include<iostream>
using namespace std;
void main()
{
int *p;
//int a[10] = { 0 };
//p = a;
int a = 100;
p=&a;
cout << "1. "<<p <<" "<<*p<< endl;
p++;
cout << "2. " << p << " " << *p << endl;
++p;
cout << "3. " << p << " " << *p << endl;
++*p;
cout << "4. " << p << " " << *p << endl;
++(*p);
cout << "5. " << p << " " << *p << endl;
++*(p);
cout << "6. " << p << " " << *p << endl;
*p++;
cout << "7. " << p << " " << *p << endl;
(*p)++; //This is the problem, increments the address by 1, even though its in int type
cout << "8. " << p << " " << *p << endl;
*(p)++;
cout << "9. " << p << " " << *p << endl;
*++p;
cout << "10. " << p << " " << *p << endl;
*(++p);
cout << "11. " << p << " " << *p << endl;
cin.get();
}
【问题讨论】:
-
在此声明中 (*p)++;地址本身不会增加。后递增的是 *p 的值。
-
@VladfromMoscow 不幸的是,我无法在此处发布输出的屏幕截图,但地址正在递增 1。地址从 00C1FA14 变为 00C1FA15。
-
在任何情况下程序都有未定义的行为。
-
你在“cout