//指针和数组
#include<iostream>
#include<iomanip> //setw()
using namespace std;
int main() {
int var[3] = {10, 100, 200};
int *ptr;
ptr=var;//指针指向数组的首地址
cout<<"var:"<<var<<" *var:"<<*var<<endl;
cout<<"ptr:"<<ptr<<" *ptr:"<<*ptr<<endl;
for (int i = 0; i < 3; i++) {
*var = i;//这是正确的语法;数组名var指向数组的首地址,所以只改变了数组的第一个元素
//var++; //这是不正确的:var作为一个常量,不能作为左值
}
cout<<"遍历数组:"<<endl;
for(int j=0;j<3;j++){
cout<<setw(8)<<var[j]<<endl;
cout<<"*ptr:"<<setw(3)<<*ptr<<" ptr:"<<ptr<<endl;
ptr++;//指向的是整数型数组,所以每次自增,地址都是自增4
}
cout<<"\n结束后指针位置:\n"<<"ptr:"<<ptr<<" *ptr:"<<*ptr<<endl;
return 0;
}
输出结果:
var:0x70fdf0 *var:10
ptr:0x70fdf0 *ptr:10
遍历数组:
2
*ptr: 2 ptr:0x70fdf0
100
*ptr:100 ptr:0x70fdf4
200
*ptr:200 ptr:0x70fdf8
结束后指针位置:
ptr:0x70fdfc *ptr:0