我知道这是一个非常基本的问题,但在用高级语言编写了几个项目之后,我刚刚开始了一些基本的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++多态性。

真的,仔细想想,这是有道理的。当您使用子类型多态性时,最终,您不知道将调用哪个类或子类的方法实现,因为您不知道实际的类是什么。

使用变量保存未知类的对象的想法与c++在堆栈上存储对象的默认(非指针)模式不兼容,在堆栈中分配的空间量直接对应于类。注意:如果一个类有5个而不是3个实例字段,则需要分配更多的空间。

请注意,如果您使用'&'通过引用传递参数,在幕后仍然涉及到间接(即指针)。'&'只是语法糖,它(1)省去了使用指针语法的麻烦,(2)允许编译器更严格(例如禁止空指针)。

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。

指针的一种用途(我不会提及在其他人的文章中已经介绍过的内容)是访问未分配的内存。这对于PC编程来说没什么用,但是在嵌入式编程中用于访问内存映射的硬件设备。

在DOS的旧时代,你可以通过声明一个指针直接访问显卡的显存:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

许多嵌入式设备仍然使用这种技术。

因为到处复制大对象会浪费时间和内存。

在很大程度上,指针是数组(在C/ c++中)——它们是内存中的地址,如果需要(在“正常”情况下),可以像数组一样访问它们。

因为它们是一个项目的地址,所以它们很小:它们只占用一个地址的空间。由于它们很小,将它们发送到函数是很便宜的。然后它们允许该函数在实际项目上工作,而不是一个副本。

如果您想进行动态存储分配(例如对于链表),则必须使用指针,因为它们是从堆中获取内存的唯一方法。