数组语法与在C函数的参数指针语法 [英] Array syntax vs. pointer syntax in C function parameters
问题描述
据我了解阵列如何衰减到指针。我明白,编译器,这样的:
I understand how arrays decay to pointers. I understand that, for the compiler, this:
void foo(int *arg1);
相当于100%这样的:
is 100% equivalent to this:
void foo(int arg1[]);
如果一个样式preferred比其他?我想是一致的,但我有一个很难证明或者决定。
Should one style be preferred over the other? I want to be consistent, but I'm having a hard time justifying either decision.
虽然 INT主(INT ARGC,CHAR *的argv [])
和 INT主(INT ARGC,字符** argv的)
都是一样的,前者似乎更为常见(纠正我,如果我错了)。
Although int main(int argc, char *argv[])
and int main(int argc, char **argv)
are the same, the former seems to be much more common (correct me if I'm wrong).
推荐答案
我会推荐的针对使用函数的参数 []
语法。
I would recommend against using the []
syntax for function parameters.
赞成使用的一个参数 []
的是,它意味着,在自记录方式,即指针有望指向一个以上的事情。例如:
The one argument in favour of using []
is that it implies, in a self-documenting way, that the pointer is expected to point to more than one thing. For example:
void swap(int *x, int *y)
double average(int vals[], int n)
不过,为什么是的char *
总是用于字符串,而不是的char []
?我宁愿是一致的,而应使用 *
。
But then why is char *
always used for strings rather than char []
? I'd rather be consistent and always use *
.
有些人喜欢,他们可能可以常量
的一切,包括通过噪声值参数。
Some people like to const
everything they possibly can, including pass-by-value parameters. The syntax for that when using []
(available only in C99) is less intuitive and probably less well-known:
为const char * const的* const的话
与为const char * const的字[常量]
虽然我认为这最后常量是矫枉过正,在任何情况下。
Although I do consider that final const
to be overkill, in any case.
此外,该阵列的的方式衰减的不完全直观。特别是,它是的不可以应用递归(字符字[] []
不工作)。尤其是当你开始在更多的间接投掷,在 []
语法只是造成混乱。 IMO最好是始终使用指针语法,而不是一个数组作为参数传递pretending。
Furthermore, the way that arrays decay is not completely intuitive. In particular, it is not applied recursively (char words[][]
doesn't work). Especially when you start throwing in more indirection, the []
syntax just causes confusion. IMO it is better to always use pointer syntax rather than pretending that an array is passed as an argument.
更多信息:的http:// C- faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr#aryptrparam 。
这篇关于数组语法与在C函数的参数指针语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!