为什么即使数组衰减到 POINTERS,将函数的参数保持为 ARRAY 也可以? [英] How come even though arrays decay to POINTERS, its fine to keep the parameter of the function as an ARRAY?

查看:67
本文介绍了为什么即使数组衰减到 POINTERS,将函数的参数保持为 ARRAY 也可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我的英语不好,

让我澄清一下,这是一个例子,

let me clarify, here is an example,

这是我们的主要内容:

 main()
{
  int a1 []= {1,2,3,4,5,6,7,8,9} ;
  int size = sizeof(a1) /sizeof(a1[0]) ;
  point (a1 , size);

  return 0 ;
}

这是函数:

void point(int a[] , int size)
{
  int i ;
  for (i = 0 ; i<size ; i++)
  printf("%d\n", a[i])) ;
}

据我所知,当一个数组作为参数传递给一个函数时,我们实际上是在发送一个指向数组第一个元素的指针..

From my knowledge, when an array is passed as an argument to a function, we are actually sending a pointer to the first element to the array..

话虽如此,为什么函数point"的参数是 ARRAY 变量,而不是 POINTER 变量......?

With that being said, how come the function "point"'s parameter is an ARRAY variable, NOT a POINTER variable...?

我认为这很奇怪的原因,例如在 main 中我们将 int* 传递给某个函数:

The reason I thought this was weird, so for example in main we pass int* to some function :

  int* a = &b ;
  point2(a) ;

函数:

void point2 (int  a) // this would be invalid, it has to be int* a
{
  .
  .
}

我们必须指定函数接收一个指针,数组如何成为异常?

We would have to specify that the function receives a pointer, How are arrays an exception?

请注意:我确实理解数组会衰减为指针;这就是为什么我的问题从来不是为什么我们可以将数组作为参数发送给具有相同类型指针的函数?".我的问题是,为什么即使数组衰减到 POINTERS,将函数的参数保持为 ARRAY 也可以?".希望很清楚这与第一个问题有何不同.谢谢!

PLEASE NOTE: I do understand that arrays decay to pointers; that's why my question never was "why can we send arrays as arguments, to functions that have pointers of that same type?". My question is, "How come even though arrays decay to POINTERS, its fine to keep the parameter of the function as an ARRAY?". Hope it is clear how this is different that the first question. Thank you!

推荐答案

C 和 C++ 的语言规范都声明T 类型数组的函数参数被调整 键入指向 T 的指针.所以这些函数声明是一回事:

The language specifications of both C and C++ state that a function parameter of type array of T is adjusted to type pointer to T. So these function declarations are one and the same:

void foo(int a[42]);
void foo(int a[]);
void foo(int* a);

所有这些都将接受一个指针参数,无论它是否是数组衰减的结果.

All of these will accept a pointer parameter, be it the result of an array decay or not.

这篇关于为什么即使数组衰减到 POINTERS,将函数的参数保持为 ARRAY 也可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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