数组语法与在C函数的参数指针语法

编程入门 行业动态 更新时间:2024-10-27 22:35:01
本文介绍了数组语法与在C函数的参数指针语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据我了解阵列如何衰减到指针。我明白,编译器,这样的:

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/~scs/cgi-bin/faqcat.cgi?sec=aryptr#aryptrparam 。

更多推荐

数组语法与在C函数的参数指针语法

本文发布于:2023-07-30 00:17:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   数组   指针   函数   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!