指向整数数组的指针与指向整数的双指针 [英] Pointer to Integer Array versus Double Pointer to Integer

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

问题描述

我会认为整数数组的类型为指向整数的指针,所以这意味着整数数组的类型为指向整数的双指针.但是我得到的结果却相反.我怀疑整数数组的类型不是指向整数的指针.

I would have thought that an integer array is of type pointer to integer, so that would mean that a pointer to an integer array is of type double pointer to integer. But the results that I am getting say otherwise. I have suspicion that the type integer array is not of type pointer to integer.

这是我的例子:

int main(){
  int p[3]={1,2,3};
  int (*ptr)[3] = &p;
  int **ptr2 = &p;

  printf("%d\n",(*ptr)[0]);
  printf("%d\n",**ptr2);
  return 0;
}

p 是3型元素整数数组.

p is of type 3 element integer array.

& p 的类型为指向3个元素整数数组的指针.

&p is of type pointer to 3 element integer array.

ptr 是指向3个元素整数数组的指针.

ptr is of type pointer to 3 element integer array.

ptr2 类型为指向整数的双指针

ptr2 is of type double pointer to integer

所以我的问题是,如果整数数组是指向整数的指针,为什么 ptr2 不能按预期工作?指向整数的类型双指针与指向整数数组的类型指针是否不同?任何帮助我解决此问题的帮助将不胜感激.谢谢!

So my question is, if an integer array is a pointer to integer, why doesn't ptr2 work as expected? Is the type double pointer to integer different from the type pointer to integer array? Any help clearing this up for me would be appreciated. Thank you!

推荐答案

我会认为整数数组的类型是指向整数的指针

I would have thought that an integer array is of type pointer to integer,

不是.在许多常见情况下,数组会衰变指向指针,但是它们并不相同.

It is not. Arrays decays to pointers in many common circumstances, but they are not the same.

所以这意味着指向整数数组的指针的类型为指向整数的双指针.

so that would mean that a pointer to an integer array is of type double pointer to integer.

不,不是.

为什么ptr2无法按预期工作?

why doesn't ptr2 work as expected?

ptr2 是一个指针,其中包含数组 p 的地址.用 * ptr2 取消引用将在 p 中给出第一个元素.再次取消引用将使用 p 中的第一个元素作为地址,并提供该地址处的值.

ptr2 is a pointer that contains the address of the array p. Dereferencing this with *ptr2 would give the first element in p. Dereferencing this again would use the first element in p as an address, and give the value at that address.

这就是为什么您应该从编译器中读取警告的原因.即使没有标志 -Wall -Wextra (您应始终使用),该代码也会发出以下警告:

This is why you should read the warnings from your compiler. Even without the flags -Wall and -Wextra (which you always should use) this code emits this warning:

k.c:6:16: warning: initialization of ‘int **’ from incompatible pointer type ‘int (*)[3]’ [-Wincompatible-pointer-types]
   int **ptr2 = &p;
                ^

那里有纯文本格式. int ** int(*)[3]

There you have it in plain text. int ** is not compatible with int(*)[3]

始终阅读编译器警告.

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

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