多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# C++ 中的指针 > 原文: [https://beginnersbook.com/2017/08/cpp-pointers/](https://beginnersbook.com/2017/08/cpp-pointers/) 指针是 C++ 中的一个变量,它包含另一个变量的地址。它们的[数据类型](https://beginnersbook.com/2017/08/cpp-data-types/)就像变量一样,例如整数类型指针可以保存整数变量的地址,字符类型指针可以保存`char`变量的地址。 #### 指针的语法 ```cpp data_type *pointer_name; ``` **如何声明指针?** ```cpp /* 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`的地址。要将变量的地址赋值给指针,我们使用**`&`符号**。 ```cpp /* This is how you assign the address of another variable * to the pointer */ p = &var; ``` **如何使用它?** ```cpp // This will print the address of variable var cout<<&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; ``` ## 指针示例 让我们举一个简单的例子来理解我们上面讨论的内容。 ```cpp #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; } ``` **输出:** ```cpp Address of var: 0x7fff5dfffc0c Address of var: 0x7fff5dfffc0c Address of p: 0x7fff5dfffc10 Value of var: 101 ``` ## 指针和数组 在使用指针处理[数组](https://beginnersbook.com/2017/08/cpp-arrays/)时,您需要注意一些事情。关于数组的第一个也是非常重要的注意事项是,数组名称单独表示数组的基地址,因此在将数组地址赋值给指针时不要使用符号(`&`)。这样做: **正确:**因为`arr`代表数组的地址。 ```cpp p = arr; ``` **不正确:** ```cpp p = &arr; ``` ### 示例:使用指针遍历数组 ```cpp #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; } ``` **输出:** ```cpp 1 2 3 4 5 6 ``` ## 如何递增指针地址和指针的值? 当我们通过指针访问变量的值时,有时我们只需要增加或减少变量的值,或者我们可能需要将指针移动到下一个`int`位置(就像我们在使用数组时一样)。 [`++`运算符](https://beginnersbook.com/2017/08/cpp-operators/)用于此目的。我们在上面看到的`++`运算符的一个示例,我们通过使用`++`运算符递增指针值来遍历数组。让我们看几个案例。 ```cpp // 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); ```