指针是 C++ 中的一个变量,它包含另一个变量的地址。它们的数据类型就像变量一样,例如整数类型指针可以保存整数变量的地址,字符类型指针可以保存char变量的地址。
指针的语法
data_type *pointer_name;
如何声明指针?
/* This pointer p can hold the address of an integer * variable, here p is a pointer and var is just a * simple integer variable */int *p, var
赋值
如上所述,整数类型指针可以保存另一个int变量的地址。这里我们有一个整数变量var和指针p,它保存var的地址。要将变量的地址赋值给指针,我们使用&符号。
/* This is how you assign the address of another variable * to the pointer */p = &var;
如何使用它?
// This will print the address of variable varcout<<&var; /* This will also print the address of variable * var because the pointer p holds the address of var */cout<<p; /* This will print the value of var, This is * important, this is how we access the value of * variable through pointer*/cout<<*p;
指针示例
让我们举一个简单的例子来理解我们上面讨论的内容。
#include <iostream>using namespace std;int main(){ //Pointer declaration int *p, var=101; //Assignment p = &var; cout<<"Address of var: "<<&var<<endl; cout<<"Address of var: "<<p<<endl; cout<<"Address of p: "<<&p<<endl; cout<<"Value of var: "<<*p; return 0;}输出:
Address of var: 0x7fff5dfffc0cAddress of var: 0x7fff5dfffc0cAddress of p: 0x7fff5dfffc10Value of var: 101
指针和数组
在使用指针处理数组时,您需要注意一些事情。关于数组的第一个也是非常重要的注意事项是,数组名称单独表示数组的基地址,因此在将数组地址赋值给指针时不要使用符号(&)。这样做:
正确:因为arr代表数组的地址。
p = arr;
不正确:
p = &arr;
示例:使用指针遍历数组
#include <iostream>using namespace std;int main(){ //Pointer declaration int *p; //Array declaration int arr[]={1, 2, 3, 4, 5, 6}; //Assignment p = arr; for(int i=0; i<6;i++){ cout<<*p<<endl; //++ moves the pointer to next int position p++; } return 0;}输出:
123456
如何递增指针地址和指针的值?
当我们通过指针访问变量的值时,有时我们只需要增加或减少变量的值,或者我们可能需要将指针移动到下一个int位置(就像我们在使用数组时一样)。 ++运算符用于此目的。我们在上面看到的++运算符的一个示例,我们通过使用++运算符递增指针值来遍历数组。让我们看几个案例。
// Pointer moves to the next int position (as if it was an array)p++; // Pointer moves to the next int position (as if it was an array) ++p; /* All the following three cases are same they increment the value * of variable that the pointer p points. */++*p; ++(*p); ++*(p);
