我知道这是一个非常基本的问题,但在用高级语言编写了几个项目之后,我刚刚开始了一些基本的c++编程。
基本上我有三个问题:
为什么使用指针而不是普通变量? 我应该在何时何地使用指针? 如何在数组中使用指针?
我知道这是一个非常基本的问题,但在用高级语言编写了几个项目之后,我刚刚开始了一些基本的c++编程。
基本上我有三个问题:
为什么使用指针而不是普通变量? 我应该在何时何地使用指针? 如何在数组中使用指针?
当前回答
指针是获得对另一个变量的间接引用的一种方式。它们不是保存变量的值,而是告诉您变量的地址。这在处理数组时特别有用,因为使用指向数组中第一个元素(它的地址)的指针,可以通过递增指针(指向下一个地址位置)快速找到下一个元素。
我读过的关于指针和指针算术的最好解释是在K & R的《C编程语言》中。开始学习c++的一本好书是c++ Primer。
其他回答
以下是我的答案,我不会保证自己是专家,但我在我正在编写的一个库中发现了很棒的指针。在这个库中(它是一个带有OpenGL的图形API:-)),你可以创建一个带有顶点对象的三角形。draw方法取这些三角形对象,然后。根据我创建的顶点对象绘制它们。嗯,没关系。
但是,如果我改变顶点坐标呢?移动它或者在顶点类中使用moveX() ?好吧,现在我必须更新三角形,添加更多的方法和性能是浪费的,因为我必须更新三角形每次顶点移动。虽然不是什么大事,但也没那么好。
现在,如果我有一个有大量顶点和三角形的网格,网格在旋转,移动,等等。我必须更新使用这些顶点的每个三角形,可能在场景中的每个三角形,因为我不知道哪个使用哪个顶点。这需要大量的计算机,如果我在一个景观上有几个网格,天哪!我遇到麻烦了,因为我更新了每个三角形,几乎每一帧,因为这些顶点一直在变化!
对于指针,你不需要更新三角形。
If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.
指针的一种用途(我不会提及在其他人的文章中已经介绍过的内容)是访问未分配的内存。这对于PC编程来说没什么用,但是在嵌入式编程中用于访问内存映射的硬件设备。
在DOS的旧时代,你可以通过声明一个指针直接访问显卡的显存:
unsigned char *pVideoMemory = (unsigned char *)0xA0000000;
许多嵌入式设备仍然使用这种技术。
在某些情况下,需要函数指针来使用共享库(. dll或.so)中的函数。这包括跨语言执行工作,其中通常提供DLL接口。 使编译器 制作科学计算器,你有一个数组或向量或字符串映射函数指针? 尝试直接修改显存-制作自己的图形包 做一个API! 数据结构-用于您正在制作的特殊树的节点链接指针
使用指针有很多原因。如果您想要保持跨语言兼容性,那么在dll中使用C名编辑尤其重要。
Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update memory in one location and the change can be seen from another location in your program. You will also save space by being able to share components in your data structures. You should use pointers any place where you need to obtain and pass around the address to a specific spot in memory. You can also use pointers to navigate arrays: An array is a block of contiguous memory that has been allocated with a specific type. The name of the array contains the value of the starting spot of the array. When you add 1, that takes you to the second spot. This allows you to write loops that increment a pointer that slides down the array without having an explicit counter for use in accessing the array.
下面是一个C语言的例子:
char hello[] = "hello";
char *p = hello;
while (*p)
{
*p += 1; // increase the character by one
p += 1; // move to the next spot
}
printf(hello);
打印
ifmmp
因为它取每个字符的值并加1。
在很大程度上,指针是数组(在C/ c++中)——它们是内存中的地址,如果需要(在“正常”情况下),可以像数组一样访问它们。
因为它们是一个项目的地址,所以它们很小:它们只占用一个地址的空间。由于它们很小,将它们发送到函数是很便宜的。然后它们允许该函数在实际项目上工作,而不是一个副本。
如果您想进行动态存储分配(例如对于链表),则必须使用指针,因为它们是从堆中获取内存的唯一方法。