我知道这是一个非常基本的问题,但在用高级语言编写了几个项目之后,我刚刚开始了一些基本的c++编程。

基本上我有三个问题:

为什么使用指针而不是普通变量? 我应该在何时何地使用指针? 如何在数组中使用指针?


当前回答

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

其他回答

这里有一个略有不同,但有深刻见解的观点,为什么C的许多特性是有意义的:http://steve.yegge.googlepages.com/tour-de-babel#C

基本上,标准的CPU体系结构是Von Neumann体系结构,在这样的机器上,能够引用内存中数据项的位置并对其进行运算是非常有用的。如果您了解汇编语言的任何变体,您将很快看到这在低级别上是多么重要。

c++让指针有点令人困惑,因为它有时会为你管理指针,并以“引用”的形式隐藏它们的效果。如果你直接使用C语言,对指针的需求就更加明显了:没有其他方法可以实现引用调用,它是存储字符串的最佳方式,是迭代数组的最佳方式,等等。

指针在许多数据结构中非常重要,这些数据结构的设计要求能够有效地将一个“节点”链接到另一个“节点”。你不会“选择”指针而不是普通的数据类型,比如float,它们只是有不同的用途。

指针在需要高性能和/或紧凑内存占用的地方非常有用。

数组中第一个元素的地址可以赋值给一个指针。这允许您直接访问底层已分配的字节。数组的全部意义就是避免你需要这样做。

这里描述了C语言中指针的需求

其基本思想是,语言中的许多限制(如使用数组、字符串和修改函数中的多个变量)可以通过操纵数据的内存位置来消除。为了克服这些限制,C语言中引入了指针。

此外,还可以看到,使用指针,您可以更快地运行代码,并在将大数据类型(如具有许多字段的结构)传递给函数时节省内存。在传递之前复制此类数据类型将花费时间并消耗内存。这是程序员更喜欢大数据类型指针的另一个原因。

PS:请参考提供的详细解释和示例代码链接。

使用指针的一个原因是可以在被调用的函数中修改变量或对象。

在c++中,使用引用比使用指针更好。虽然引用本质上是指针,但c++在某种程度上隐藏了这一事实,让它看起来好像是通过值传递的。这使得更改调用函数接收值的方式变得很容易,而不必修改传递值的语义。

考虑以下例子:

使用引用:

public void doSomething()
{
    int i = 10;
    doSomethingElse(i);  // passes i by references since doSomethingElse() receives it
                         // by reference, but the syntax makes it appear as if i is passed
                         // by value
}

public void doSomethingElse(int& i)  // receives i as a reference
{
    cout << i << endl;
}

使用指针:

public void doSomething()
{
    int i = 10;
    doSomethingElse(&i);
}

public void doSomethingElse(int* i)
{
    cout << *i << endl;
}

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。