如何在 C/C++ 中声明指针变量?


指针用于存储变量的地址。要在 C/C++ 中声明指针变量,在变量名前使用星号 (*)。

声明

*pointer_name

在 C 中

示例

 实时演示

#include <stdio.h>
int main() {
   // A normal integer variable
   int a = 7;
   // A pointer variable that holds address of a.
   int *p = &a;
   // Value stored is value of variable "a"
   printf("Value of Variable : %d\n", *p);
   //it will print the address of the variable "a"
   printf("Address of Variable : %p\n", p);
   // reassign the value.
   *p = 6;
   printf("Value of the variable is now: %d\n", *p);
   return 0;
}

输出

Value of Variable : 7
Address of Variable : 0x6ffe34
Value of the variable is now: 6

在 C++ 中

示例

 实时演示

#include <iostream>
using namespace std;
int main() {
   // A normal integer variable
   int a = 7;
   // A pointer variable that holds address of a.
   int *p = &a;
   // Value stored is value of variable "a"
   cout<<"Value of Variable : "<<*p<<endl;
   //it will print the address of the variable "a"
   cout<<"Address of Variable : "<<p<<endl;
   // reassign the value.
   *p = 6;
   cout<<"Value of the variable is now: "<<*p<<endl;
   return 0;
}

输出

Value of Variable : 7
Address of Variable : 0x6ffe34
Value of the variable is now: 6

更新于: 30-7-2019

429 次浏览

开启你的 职业

通过完成课程获得认证

开始
广告