大佬教程收集整理的这篇文章主要介绍了指针变量是什么,C++指针变量详解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
int *ptr;
变量名前面的星号(*)表示 ptr 是一个指针变量,int 数据类型表示 ptr 只能用来指向或保存整数变量的地址。这个定义读为 "ptr 是一个指向 int 的指针",也可以将 *ptr 视为 "ptr 指向的变量"。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
The address of x is 0x7e00
ptr = &x;
图 1 说明了 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:
25 25
Once again,here is the value in x:
100 100
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:
25 50 75
Once again,here are the values of x,and z:
50 100 150
以上是大佬教程为你收集整理的指针变量是什么,C++指针变量详解全部内容,希望文章能够帮你解决指针变量是什么,C++指针变量详解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。