取地址运算符&用法
#include<iostream>
using namespace std;
int main()
{
int donuts=6;
double cups=4.5;
cout<<"donuts value = "<<donuts;
cout<<" and donuts address = "<<&donuts<<endl;
cout<<"cups value = "<<cups;
cout<<" and cups address = "<<&cups<<endl;
system("pause");
return 0;
}
间接值运算符的使用
#include<iostream>
using namespace std;
int main()
{
int donuts=6;
int updates=6;
int *p_updates;
p_updates=&updates;
cout<<"Values:updates = "<<updates;
cout<<",*p_updates = "<<*p_updates<<endl;
cout<<"Addresses:&updates = "<<&updates;
cout<<",p_updates = "<<p_updates<<endl;
*p_updates=*p_updates+1;
cout<<"Now updates = "<<updates<<endl;
system("pause");
return 0;
}
将指针初始化为一个地址
#include<iostream>
using namespace std;
int main()
{
int higgens=5;
int* pt=&higgens;
cout<<" Value of higgens = "<<higgens
<<"; Address of higgens = "<<&higgens<<endl;
cout<<"Value of *pt = "<<*pt
<<"; Value of pt = "<<pt<<endl;
system("pause");
return 0;
}
将new用于两种不同的类型
#include<iostream>
using namespace std;
int main()
{
int nights=1001;
int *pt=new int;
*pt=1001;
cout<<"night value = ";
cout<<nights<<":location "<<&nights<<endl;
cout<<"int ";
cout<<"value = "<<*pt<<":location = "<<pt<<endl;
double* pd=new double;
*pd=10000001.0;
cout<<"double ";
cout<<"value = "<<*pd<<":location = "<<pd<<endl;
cout<<"location of pointer pd:"<<&pd<<endl;
cout<<"Size of pt = "<<sizeof(pt);
cout<<":size of *pt = "<<sizeof(*pt)<<endl;
cout<<"size of pd = "<<sizeof pd;
cout<<":size of *pd = "<<sizeof(*pd)<<endl;
system("pause");
return 0;
}
使用new来创建动态数组及其使用数组表示法来访问数组,指出指针和真正数组名之间的根本差别:指针是变量,数组名是地址。
#include<iostream>
using namespace std;
int main()
{
double* p3=new double[3];
p3[0]=0.2;
p3[1]=0.5;
p3[2]=0.8;
cout<<"p3[1] is "<<p3[1]<<".\n";
p3=p3+1;
cout<<"Now p3[0] is "<<p3[0]<<" and ";
cout<<"p3[1] is "<<p3[1]<<".\n";
p3=p3-1;
delete [] p3;
system("pause");
return 0;
}
指针、数组和指针算术
#include<iostream>
using namespace std;
int main()
{
double wages[3]={10000.0,20000.0,30000.0};
short stacks[3]={3,2,1};
double* pw= wages;
short* ps=&stacks[0];
cout<<"pw = "<<pw<<", *pw = "<<*pw<<endl;
pw=pw+1;
cout<<"add 1 to the pw pointer:\n";
cout<<"pw = "<<pw<<",*pw= "<<*pw<<"\n\n";
cout<<"ps = "<<ps<<",*ps= "<<*ps<<endl;
ps=ps+1;
cout<<"add 1 to the ps pointer:\n";
cout<<"ps = "<<ps<<",*ps = "<<*ps<<"\n\n";
cout<<"acceess two elements with arry notation\n";
cout<<"stacks[0] = "<<stacks[0]
<<",stacks[1] = "<<stacks[1]<<endl;
cout<<"access two elements with pointer notation\n";
cout<<"*stacks = "<<*stacks
<<",*(stacks+1) = "<<*(stacks+1)<<endl;
cout<<sizeof(wages)<<" = size of wages array\n";
cout<<sizeof(pw)<<" = size of pw pointer\n";
system("pause");
return 0;
}
posted on
浙公网安备 33010602011771号