C语言中的指针对指针如何工作?(以及什么时候可以使用它们?) [英] How do pointer-to-pointer's work in C? (and when might you use them?)

查看:60
本文介绍了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  | \0 |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

在这里您可以看到,在地址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.

关于为什么使用指针的指针:

  • 数组的名称通常会产生其第一个元素的地址.因此,如果数组包含类型为 t 的元素,则对该数组的引用的类型为 t * .现在考虑一个类型为 t 的数组的数组:自然地,对此2D数组的引用将具有类型为(t *)* = t ** ,因此是指向指针的指针.
  • 尽管字符串数组听起来是一维的,但实际上它是二维的,因为字符串是字符数组.因此: char ** .
  • 如果函数 f 要更改类型为 t * 的变量,则需要接受类型为 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天全站免登陆