01指针的定义和使用
#include <iostream> ;
using namespace std;
int main ( ) {
int a = 10 ;
int * p;
p = & a;
cout << "a=" << a << endl;
cout << "a的地址:" << & a << endl;
cout << "指针p的值:" << p << endl;
* p = 1000 ;
cout << "a=" << a << endl;
system ( "pause" ) ;
return 0 ;
}
02指针所占内存空间
#include <iostream> ;
using namespace std;
int main ( ) {
int a = 10 ;
int * p;
p = & a;
cout << "sizeof(int *)=" << sizeof ( int * ) << endl;
cout << "sizeof(float *)=" << sizeof ( float * ) << endl;
cout << "sizeof(double *)=" << sizeof ( double * ) << endl;
cout << "sizeof(char *)=" << sizeof ( char * ) << endl;
system ( "pause" ) ;
return 0 ;
}
03空指针和野指针
#include <iostream> ;
using namespace std;
int main ( ) {
int a = 10 ;
int * p1= NULL ;
system ( "pause" ) ;
return 0 ;
}
04const修饰指针
#include <iostream> ;
using namespace std;
int main ( ) {
int a = 10 ;
int b = 20 ;
const int * p1 = & a;
p1 = & b;
int * const p2 = & a;
* p2 = b;
const int * const p3 = & a;
system ( "pause" ) ;
return 0 ;
}
05指针和数组
#include <iostream> ;
using namespace std;
int main ( ) {
int arr[ 10 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ;
cout << "数组中的第一个元素" << arr[ 0 ] << endl;
int * p = arr;
cout << "p指向地址的值为" << * p << endl;
p++ ;
cout << "p++指向地址的值为" << * p << endl;
p = arr;
for ( int i = 0 ; i < 10 ; i++ ) {
cout << "p指向地址的值为" << * p << endl;
p++ ;
}
system ( "pause" ) ;
return 0 ;
}
06指针和函数
#include <iostream> ;
using namespace std;
void swap01 ( int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
void swap02 ( int * p1, int * p2) {
int temp = * p1;
* p1 = * p2;
* p2 = temp;
}
int main ( ) {
int a = 10 ;
int b = 20 ;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "未交换" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
swap01 ( a, b) ;
cout << "普通值传递交换" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
swap02 ( & a, & b) ;
cout << "使用指针交换" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system ( "pause" ) ;
return 0 ;
}