本文介绍了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函数参数中的数组语法与指针语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:50