指针的指针与正常指针 [英] Pointers to pointers vs. normal pointers

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

问题描述

的指针的目的是为了保存特定变量的地址。然后按照code的存储结构应该是这样的:

  int类型的= 5;
为int * B =&放大器;一个;


  

......内存地址......值

  一个... 0x000002 ................... 5

  b ... 0x000010 ................... 0x000002


好,好。再假设现在我要救指针* b的地址。然后,我们通常定义一个双指针,** C,如

  int类型的= 5;
为int * B =&放大器;一个;
INT ** C =和b;

那么内存结构如下:


  

......内存地址......值

  一个... 0x000002 ................... 5

  b ... 0x000010 ................... 0x000002

  ç... 0x000020 ................... 0x000010


所以,** C指* b的地址。

现在我的问题是,为什么这种类型的code的,

  int类型的= 5;
为int * B =&放大器;一个;
INT * C =和b;

生成一个警告?

如果指针的目的只是为了节省内存地址,我觉得不应该有层次,如果我们要保存地址指的是一个变量,指针,双指针等,这样下面的类型$的C $ C应该有效。

  int类型的= 5;
为int * B =&放大器;一个;
INT * C =和b;
为int * D =和C;
为int * E =和D;
为int * F =急症室;


解决方案

  int类型的= 5;
为int * B =&放大器;一个;
INT * C =和b;

您得到一个警告,因为和b 的类型为 INT ** ,并尝试初始化类型的变量为int * 。有这两种类型之间不存在隐式转换,导致了警告。

要带你想要的工作,如果我们试图取消引用更长的例子˚F编译器会给出我们一个 INT ,不是指针,我们可以进一步取消引用。

另外请注意,在许多系统上 INT 为int * 是不一样的尺寸(如指针可能64位长和 INT 32位)。如果取消引用˚F,并得到一个 INT ,你失去了一半的价值,然后你甚至不能投它一个有效的指针。

The purpose of a pointer is to save the address of a specific variable. Then the memory structure of following code should look like:

int a = 5;
int *b = &a;

...... memory address ...... value
a ... 0x000002 ................... 5
b ... 0x000010 ................... 0x000002

Okay, fine. Then assume that now I want to save the address of pointer *b. Then we generally define a double pointer, **c, as

int a = 5;
int *b = &a;
int **c = &b;

Then the memory structure looks like:

...... memory address ...... value
a ... 0x000002 ................... 5
b ... 0x000010 ................... 0x000002
c ... 0x000020 ................... 0x000010

So **c refers the address of *b.

Now my question is, why does this type of code,

int a = 5;
int *b = &a;
int *c = &b;

generate a warning?

If the purpose of pointer is just to save the memory address, I think there should be no hierarchy if the address we are going to save refers to a variable, a pointer, a double pointer, etc., so the below type of code should be valid.

int a = 5;
int *b = &a;
int *c = &b;
int *d = &c;
int *e = &d;
int *f = &e;

解决方案

In

int a = 5;
int *b = &a;   
int *c = &b;

You get a warning because &b is of type int **, and you try to initialize a variable of type int *. There's no implicit conversions between those two types, leading to the warning.

To take the longer example you want to work, if we try to dereference f the compiler will give us an int, not a pointer that we can further dereference.

Also note that on many systems int and int* are not the same size (e.g. a pointer may be 64 bits long and an int 32 bits long). If you dereference f and get an int, you lose half the value, and then you can't even cast it to a valid pointer.

这篇关于指针的指针与正常指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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