指针变量是什么,C++指针变量详解
发布时间:2020-12-16 07:38:00 所属栏目:百科 来源:网络整理
导读:像其他数据值一样,内存地址或指针值可以存储在适当类型的变量中。存储地址的变量被称为 指针变量 ,但通常简称为 指针 。 指针变量(例如 ptr) 的定义必须指定 ptr 将指向的数据类型。以下是一个例子: int *ptr; 变量名前面的星号(*)表示 ptr 是一个指针
像其他数据值一样,内存地址或指针值可以存储在适当类型的变量中。存储地址的变量被称为指针变量,但通常简称为指针。 指针变量(例如 ptr) 的定义必须指定 ptr 将指向的数据类型。以下是一个例子: int *ptr; 变量名前面的星号(*)表示 ptr 是一个指针变量,int 数据类型表示 ptr 只能用来指向或保存整数变量的地址。这个定义读为 "ptr 是一个指向 int 的指针",也可以将 *ptr 视为 "ptr 指向的变量"。从这个角度上来说,刚刚给出的 ptr 的定义可以被理解为 "ptr 指向的类型为 int 的变量"。因为星号允许从指针传递到所指向的变量,所以称之为间接运算符。 有些程序员更喜欢在类型名称后面添加星号来声明指针,而不是在变量名称旁边。例如,上面显示的声明也可以写成如下形式: int* ptr; 这种声明的风格可能在视觉上强化了 ptr 的数据类型不是 int,而是 int 指针的事实。两种声明的样式都是正确的。下面的程序演示了一个非常简单的指针使用,存储和打印另一个变量的地址。 //This program stores the address of a variable in a pointer. #include <iostream> using namespace std; int main() { int x = 25; // int variable int *ptr; // Pointer variable,can point to an int ptr = &x; // Store the address of x in ptr cout << "The value in x is " << x << endl; cout << "The address of x is " << ptr << endl; return 0; }程序输出结果:
The value in x is 25 ptr = &x; 图 1 说明了 ptr 和 x 之间的关系。![]() 图 1 变量 x 和 ptr 指针之间的关系 如图 1 所示,变量 x 的内存地址为 0x7e00,它包含数字 25,而指针 ptr 包含地址 0x7e00。实质上,ptr 是“指向”变量 X。 可以使用指针来间接访问和修改指向的变量。例如在上面程序中,可以使用 ptr 来修改变量 x 的内容。当间接运算符放在指针变量名称的前面时,它将解引用指针。在使用解引用的指针时,实际上就是使用指针指向的值。下面程序演示了这一点: //This program demonstrates the use of the indirection operator. #include <iostream> using namespace std; int main() { int x = 25; // int variable int *ptr; //Pointer variable,can point to an int ptr = &x; //Store the address of x in ptr // Use both x and ptr to display the value in x cout << "Here is the value in x,printed twice:n"; cout << x << " " << *ptr << endl; //Assign 100 to the location pointed to by ptr //This will actually assign 100 to x. *ptr = 100; //Use both x and ptr to display the value in x cout << "Once again,here is the value in x:n"; cout << x << " " << *ptr << endl; return 0; }程序输出结果:
Here is the value in x,printed twice: cout << x << " " << *ptr << endl; 下面的语句可以在变量 X 中存储值 100:*ptr = 100; 通过间接运算符(*),就可以使用 ptr 间接访问它所指向的变量。下面的程序表明指针可以指向不同的变量:// This program demonstrates the ability of a pointer to point to different variables. #include <iostream> using namespace std; int main() { int x = 25,y = 50,z = 75; // Three int variables int *ptr; // Pointer variable // Display the contents of x,yr and z cout << "Here are the values of x,y,and z:n"; cout << x << " " << y << " " << z << endl; // Use the pointer to manipulate x,and z ptr = &x; // Store the address of x in ptr *ptr *= 2; // Multiply value in x by 2 ptr = &y; // Store the address of y in ptr *ptr *=2; // Multiply value in y by 2 ptr = &z; // Store the address of z in ptr *ptr *= 2; // Multiply value in z by 2 //Display the contents of x,and z cout << "Once again,here are the values " << "of x,and z:n"; cout << x << " " << y << " " << z << endl; return 0; }程序输出结果:
Here are the values of x,and z: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |