如何指针的指针的方式是C? [英] How do pointer to pointers work in C?

查看:103
本文介绍了如何指针的指针的方式是C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何指针的指针用C的工作?
当你使用它们?

How do pointers to pointers work in C? When would 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开始。因此,在这种情况下,如果这是你好在存储器中的唯一的发生,然后,

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 在位置58.当然,在上面的例子中,我们不仅可以指向人物,也给其他指针:C 本身必须存储在某个地方。例如:

... 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 **

  • 函数˚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天全站免登陆