指针复习
#include<iostream>
using namespace std;
int main()
{
//1、int *ip_a与int* ip_b,只要有*号就认为是指针变量
int ia = 5, ib = 10, ic = 13;
int *ip_a = &ia;//初始化
cout <<"*ip_a:" << *ip_a << endl;
int* ip_b = &ib;
cout << "* ip_b:" << *ip_b << endl;
//2、&是取地址运算符,*是取变量地址运算符
int d = 10;
cout << "*(&d):" << *(&d) << endl;
//3、多个赋值
double de = 100;
double *dp_e = &de, temp = 200;
cout << "dp_e:" << dp_e << endl << "temp:" << temp<<endl;
//4,在解引用指针的时候,你需要保证你的指针被正确的初始化或者正确的被赋过某个地址
//初始化为nullptr
int *pa = nullptr;
cout << "pa:" << pa << endl;
//5、void*
//Void*是一种特殊类型的指针,能够用来存放任何类型对象的地址.
//通俗来说,就是不知道这个指针指向的是什么类型的对象.
double df = 100.0;
double *d_pf = &df;
void *v_p1 = d_pf;
void *v_p2 = &df;
cout << "v_p1:" << v_p1 << endl << "v_p2:" << v_p2 << endl;
//6、指针的指针
int a = 10;
int *p = &a;
int **pp = &p;
cout << "p:" << p << endl;
cout << "pp:" << pp << endl;
return 0;
}
运行结果:
交换(????????????????)
#include"stdafx.h"
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swap_str(char **str_a, char **str_b)
{
char *temp=*str_a;
*str_a = *str_b;
*str_b = temp;
}
int main()
{
int a = 10;
int b = 5;
char *string_a="hello";
char *string_b="world";
swap(a, b);
cout << "a:" << a << endl;
cout << "b:" << b << endl;
swap_str(&string_a, &string_b);
cout << "string_a:" << string_a << endl;
cout << "string_b:" << string_b << endl;
}
参考博客:
http://blog.csdn.net/xierhacker/article/details/52516742