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

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

我理解数组如何衰减到指针。我理解,对于编译器,这是:

I understand how arrays decay to pointers. I understand that, for the compiler, this:

void foo(int *arg1);

是100%等效于此:

void foo(int arg1[]);

一种风格应该优先于另一种风格吗?

Should one style be preferred over the other? I want to be consistent, but I'm having a hard time justifying either decision.

虽然 int main(int argc,char * argv [ ])和 int main(int argc,char ** 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 *.

有些人喜欢 const 所有可能的东西,包括传值的参数。使用 [] (仅在C99中可用)的语法不那么直观,而且可能不太熟悉:

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 words 与 const char * const words [const]

虽然我认为最终的 const 是过度的,但在任何情况下。

Although I do consider that final const to be overkill, in any case.

此外,数组衰减的方式并不完全直观。特别是 不递归应用( char words [] [] 不起作用)。特别是当你开始引入更多的间接, [] 语法只会导致混乱。 IMO最好总是使用指针语法,而不是假装将数组作为参数传递。

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.

更多信息: c-faq/~scs/cgi-bin/faqcat.cgi?sec= aryptr#aryptrparam 。

更多推荐

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

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

发布评论

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

>www.elefans.com

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