What is wrong with the following code


#include<iostream>
using namespace std;
struct S
{
int i;
int *p;
};

int main()
{
//S s; // 结构体没有初始化,怎么会有地址的分配改写如下
//s.i = 1;
//int q = 2;
//s.p = &q;
//cout << "&s.i= " << &s.i << endl;
S s;
int *p = &s.i; // p 指针指向s.i,相当于int *p;p = &s.i;
cout << "p= " << p << endl;
p[0] = 4; // 相当于赋值给s.i;
p[1] = 3; // 相当于赋值给S.p,即是s.p里储存的值为3,而不是某个变量的地址
cout << "s.i= " << s.i << endl;
cout << "s.p= " << s.p << endl;
cout << "&s.i= " << &s.i << endl;
cout << "&s.p= " << &s.p << endl;
cout << "p[0]= " << p[0] << endl;
cout << "p[1]= " << p[1] << endl;
s.p = p; // 即是把00000003的值在赋给s.p,那么s.p指向的内存块的地址是00000003, s.p[1] = 1;//s.p[1]指向的地址是00000004,直接把1赋给一个不知道的内存块会出错
s.p[2] = 2;
return 0;
}


输出的结果如下:
cout << "s.i= " << s.i << endl; 4
cout << "s.p= " << s.p << endl; 00000003
cout << "&s.i= " << &s.i << endl; 0012FF5C
cout << "&s.p= " << &s.p << endl; 0012FF60
cout << "p[0]= " << p[0] << endl; 4
cout << "p[1]= " << p[1] << endl; 3
由以上输出可以看出:
1.int *p = &s.i;是把s.i的地址赋给指针P,即:p=&s.i
2.p[0]代表s.i;p[1]=s.p;
3.p[1]=3;即是s.p指针值为3,指向变量的地址为3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值