指针在 C 中是如何工作的?(你什么时候可以使用它们?) [英] How do pointer-to-pointers work in C? (and when might you use them?)

查看:26
本文介绍了指针在 C 中是如何工作的?(你什么时候可以使用它们?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

指针指向指针在 C 中是如何工作的?
您什么时候可以使用它们?

How do pointers-to-pointers work in C?
When might you use them?

推荐答案

假设一台具有 8 位地址的 8 位计算机(因此只有 256 字节的内存).这是该内存的一部分(顶部的数字是地址):

Let's assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses):

  54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    | 58 |    |    | 63 |    | 55 |    |    | h  | e  | l  | l  | o  |  |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

您可以在这里看到,在地址 63 处,字符串hello"开始.所以在这种情况下,如果这是内存中唯一出现的hello",那么,

What you can see here, is that at address 63 the string "hello" starts. So in this case, if this is the only occurrence of "hello" in memory then,

const char *c = "hello";

... 将 c 定义为指向(只读)字符串hello"的指针,因此包含值 63. c 必须自己存储某处:在上例中的位置 58.当然我们不仅可以指向字符,还可以指向其他指针.例如:

... defines c to be a pointer to the (read-only) string "hello", and thus contains the value 63. c must itself be stored somewhere: in the example above at location 58. Of course we can not only point to characters, but also to other pointers. E.g.:

const char **cp = &c;

现在cp指向c,即包含c的地址(即58).我们可以走得更远.考虑:

Now cp points to c, that is, it contains the address of c (which is 58). We can go even further. Consider:

const char ***cpp = &cp;

现在cpp存储cp的地址.所以它的值是 55(基于上面的例子),你猜对了:它本身存储在地址 60.

Now cpp stores the address of cp. So it has value 55 (based on the example above), and you guessed it: it is itself stored at address 60.

至于为什么使用指向指针的指针:

As to why one uses pointers to pointers:

  • 数组的名称通常会产生其第一个元素的地址.因此,如果数组包含 t 类型的元素,则对数组的引用具有 t * 类型.现在考虑一个 t 类型数组的数组:自然地,对这个二维数组的引用将具有类型 (t *)* = t **,因此是指向指针的指针.
  • 虽然字符串数组听起来是一维的,但实际上它是二维的,因为字符串是字符数组.因此:char **.
  • 如果要更改 t * 类型的变量,f 函数将需要接受 t ** 类型的参数.
  • 许多其他原因不胜枚举.
  • The name of an array usually yields the address of its first element. So if the array contains elements of type t, a reference to the array has type t *. Now consider an array of arrays of type t: naturally a reference to this 2D array will have type (t *)* = t **, and is hence a pointer to a pointer.
  • Even though an array of strings sounds one-dimensional, it is in fact two-dimensional, since strings are character arrays. Hence: char **.
  • A function f will need to accept an argument of type t ** if it is to alter a variable of type t *.
  • Many other reasons that are too numerous to list here.

这篇关于指针在 C 中是如何工作的?(你什么时候可以使用它们?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆