简体   繁体   English

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);

is 100% equivalent to this: 是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. 我希望保持一致,但我很难为两种决定辩护。

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). 虽然int main(int argc, char *argv[])int main(int argc, char **argv)是相同的,但前者似乎更常见(如果我错了,请纠正我)。

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)

But then why is char * always used for strings rather than char [] ? 但是为什么char *总是用于字符串而不是char [] I'd rather be consistent and always use * . 我宁愿保持一致,也总是使用*

Some people like to const everything they possibly can, including pass-by-value parameters. 有些人喜欢const他们可能做的一切,包括传值参数。 The syntax for that when using [] (available only in C99) is less intuitive and probably less well-known: 使用[]时的语法(仅在C99中可用)不太直观,可能不太为人所知:

const char *const *const words vs. const char *const words[const] const char *const *const words vs. const char *const words[const]

Although I do consider that final const to be overkill, in any case. 虽然我确实认为最终的const有点矫枉过正,无论如何。

Furthermore, the way that arrays decay is not completely intuitive. 此外,阵列衰减的方式并不完全直观。 In particular, it is not applied recursively ( char words[][] doesn't work). 特别是,它不是递归应用的char words[][]不起作用)。 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. IMO最好总是使用指针语法而不是假装数组作为参数传递。

More information: http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr#aryptrparam . 更多信息: http//c-faq.com/~scs/cgi-bin/faqcat.cgi?sec = aaryptr #aryptrparam

Except for char* , I use Type array[N] , where N is some number or a defined constant, when the passed item conceptually is an array (ie, it contains N>1 elements), Type * pointer when the passed item is a pointer to exactly one object. 除了char* ,我使用Type array[N] ,其中N是某个数字或定义的常量,当传递的项目在概念上是一个数组时(即,它包含N> 1个元素),当传递的项目Type * pointerType * pointer指向一个对象的指针。

I tend to use std::vector if the array is of a variable size. 如果数组的大小可变,我倾向于使用std::vector C99's concept of variable sized arrays is not available in C++. C99的可变大小数组的概念在C ++中不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM