什么是指针?

时间:2020-03-06 14:55:58  来源:igfitidea点击:

请参阅:了解指针

在许多C风格的语言以及某些较旧的语言(例如Fortran)中,可以使用Pointers。

作为只真正使用基本的Javascript和ActionScript进行编程的人,我们可以向我解释一下Pointer是什么,以及它最有用的是什么?

谢谢!

解决方案

指针是一个变量,其中包含另一个变量的地址。这使我们可以间接引用另一个变量。例如,在C中:

// x is an integer variable
int x = 5;
// xpointer is a variable that references (points to) integer variables
int *xpointer;
// We store the address (& operator) of x into xpointer.
xpointer = &x;
// We use the dereferencing operator (*) to say that we want to work with
// the variable that xpointer references
*xpointer = 7;
if (5 == x) {
    // Not true
} else if (7 == x) {
    // True since we used xpointer to modify x
}

这篇维基百科文章将为我们提供有关指针是什么的详细信息:

In computer science, a pointer is a programming language data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address. Obtaining or requesting the value to which a pointer refers is called dereferencing the pointer. A pointer is a simple implementation of the general reference data type (although it is quite different from the facility referred to as a reference in C++). Pointers to data improve performance for repetitive operations such as traversing string and tree structures, and pointers to functions are used for binding methods in Object-oriented programming and run-time linking to dynamic link libraries (DLLs).

如前所述,指针是一个变量,其中包含另一个变量的地址。

它主要在创建新对象时使用(在运行时)。

在SO中已经有一些关于该主题的讨论。我们可以通过以下链接找到有关该主题的信息。关于此主题还有其他一些相关的SO讨论,但我认为这些讨论最相关。在搜索窗口中搜索" pointers [C ++]"(或者" pointers [c]"),我们还将获得更多信息。

在C ++中,我无法掌握指针和类

现代参考和传统指针有什么区别?

指针并不像听起来那样难。正如其他人已经说过的那样,它们是保存其他变量地址的变量。假设我想给我们指示去我家的路。我不会给你我家的照片或者我家的比例模型;我只想给你地址。我们可以从中推断出我们需要的一切。

同样,许多语言在按值传递和按引用传递之间进行区分。从本质上讲,这意味着我每次引用该对象时都会传递整个对象吗?或者,我只是给出它的地址,以便其他人可以推断出他们需要什么?

大多数现代语言通过弄清楚指针何时有用并为我们进行优化来隐藏这种复杂性。但是,如果我们知道自己在做什么,则在某些情况下手动指针管理仍然有用。