6.2.4 利用指针改变值(2)
2.开始定义main()函数并创建一些变量。
- int main() {
- int a = -12;
- float b = 78.53;
- char c = 'D';
- unsigned long d = 1904856026;
- std::string e = "arglebargle";
你可以使用以前用过的变量,也可以使用不同的变量。为了更加全面一些,我们在这个示例程序里增加了一个string类型的变量。
3.输出各个变量的初始值。
- std::cout << "The value of a is initially "
- << a << "\n";
- std::cout << "The value of b is initially "
- << b << "\n";
- std::cout << "The value of c is initially "
- << c << "\n";
- std::cout << "The value of d is initially "
- << d << "\n";
- std::cout << "The value of e is initially "
- << e << "\n";
4.为每个变量创建一个指针。
- int *aPointer = &a;
- float *bPointer = &b;
- char *cPointer = &c;
- unsigned long *dPointer = &d;
- std::string *ePointer = &e;
你应该见过这段代码--这里只多了一个字符串指针,但它与其他指针没什么两样。现在,每个指针均分别保存着相应的变量的地址。
5.通过指针来改变各个变量的值。
- *aPointer = 5462;
- *bPointer = -3.143022489;
- *cPointer = 'Z';
- *dPointer = 1604326026;
- *ePointer = "foofarah";
要想利用指针来改变一个变量的值,需要在指针的名字前加上一个星号(*)。
6.再次输出各个变量的值。
- std::cout << "The value of a is now "
- << a << "\n";
- std::cout << "The value of b is now "
- << b << "\n";
- std::cout << "The value of c is now "
- << c << "\n";
- std::cout << "The value of d is now "
- << d << "\n";
- std::cout << "The value of e is now "
- << e << "\n";
这些cout语句将显示步骤5里的代码所做的修改。
7.完成main()函数。
- std::cout << "Press Enter or Return to continue.\n";
- std::cin.get();
- return 0;
- }
8.把这个文件保存为pointer2.cpp,然后编译并运行这个程序(如图6-14所示)。
|
图6-14 利用指针"解引用" 处理改变不同类型的变量的值 |
"提示
一定要牢记这一事实:指针所保存的是内存中的一个地址。它不保存数据值本身,也不负责为了保存该数据值而分配内存。因此,应该确保指针对应一个已经存在的变量或一块已分配的内存。
星号有两种用途,这往往会让初学者感到困惑。它的第一种用途是创建指针:
- int *myPointer = &myInt;
它的第二种用途是对指针进行解引用:
- *myPointer = 230949;
-
C++(www.cppentry.com)允许多个指针有同样的值。
- int *p1 = &myInt;
- int *p2 = &myInt;
现在,p1等于p2,它们都等于&myInt(myInt变量的地址)。进一步说,*p1等于*p2,它们都等于myInt变量的值。
C++(www.cppentry.com)支持无类型(void)指针,即没被声明为某种特定类型的指针,如下所示:
- void *pointerName;
在对一个无类型指针进行解引用前,必须先把它转换为一种适当的数据类型。我们之所以会在这里提到无类型指针,是因为你可能会在其他地方见到它们,但它们并不是为初学者准备的。
【责任编辑:
云霞 TEL:(010)68476606】