C++ s4
时间:2010-09-18 来源:luozhiyong131
#include <iostream.h>
void main(){
int a[5]={0,2,4,6,8};
int *pa;
pa = a;
for(int i=0;i<5;i++){
cout<<"a["<<i<<"] ";
}
cout<<endl;
for(i=0;i<5;i++){
cout<<a[i]<<"\t";
}
cout<<endl;
for(i=0;i<5;i++){
cout<<*(pa+i)<<"\t";
}
cout<<endl;
for(i=0;i<5;i++){
cout<<pa[i]<<'\t';
}
cout<<endl;
}
/*
利用指针访问数组中的每个元素
*/
#include <iostream.h>
void main(){
int a[5];
int *pa=a;
for (int i=0;i<5;i++){
pa[i]=2*i+1;
}
for (i=0;i<5;i++){
cout<<'\t'<<pa[i];
}
cout<<endl;
for (i=0;i<5;i++){
cout<<'\t'<<*pa;
pa++;
}
cout<<endl;
}
#include <iostream.h>
#include <string.h>
void main(){
unsigned int i;
char a[]="hello";
char *pa=a;
cout<<a<<endl;
for(i=0;i<strlen(a);i++)
cout<<pa[i];
cout<<endl;
for(i=0;i<strlen(a);i++)
cout<<(pa+i)<<'\t';
cout<<endl;
}
/*
内存动态分配与释放实例
*/
#include <iostream.h>
#include <stdlib.h>
void main(){
int *p = new int;
if(p==0){
cout<<"申请动态内存失败,程序退出!"<<endl;
exit(0);
}
*p=100;
cout<<"*p="<<*p<<endl;
delete p;
p = new int[5];
if(p==0){
cout<<"申请动态内存失败,程序退出!"<<endl;
exit(0);
}
for(int i=0;i<5;i++){
*(p+i)=2*i+1;
cout<<"p["<<i<<"] = "<<*(p+i)<<'\t';
}
delete[]p;
}
/*
引用的声明
*/
#include <iostream.h>
void main(){
int a = 15;
int &b=a;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
b=10;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}