c++语言中的指针是一个变量,它也称为定位符或指示符,它是指向一个值的地址。
指针的优点
指针的使用
在c++语言中有许多指针的使用。
动态内存分配
在c语言中,可以使用malloc()
和calloc()
函数动态分配内存,其中使用的就是指针。
数组,函数和结构体
c语言中的指针被广泛用于数组,函数和结构体中。 它减少了代码并提高了性能。
符号 | 名称 | 描述 |
---|---|---|
& |
地址运算符 | 获取变量的地址。 |
* |
间接运算符 | 访问地址的值。 |
c++语言中的指针可以使用*
(星号符号)声明。
int ∗ a; //pointer to int
char ∗ c; //pointer to char
下面来看看看使用指针打印地址和值的简单例子。
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
cout<<"address of number variable is:"<<&number<<endl;
cout<<"address of p variable is:"<<p<<endl;
cout<<"value of p variable is:"<<*p<<endl;
return 0;
}
执行上面代码得到如下结果 -
address of number variable is:0x7ffccc8724c4
address of p variable is:0x7ffccc8724c4
value of p variable is:30
在不使用第三个变量的情况下交换2个数字的指针程序示例
#include <iostream>
using namespace std;
int main()
{
int a=20,b=10,∗p1=&a,∗p2=&b;
cout<<"before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"after swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
return 0;
}
执行上面代码得到如下结果 -
address of number variable is:0x7ffccc8724c4
address of p variable is:0x7ffccc8724c4
value of p variable is:30