哪种方法最好在C中将数组作为函数参数传递? [英] Which way is better to pass arrays as function arguments in C?

查看:51
本文介绍了哪种方法最好在C中将数组作为函数参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有3种方法可以将数组作为函数参数传递.

There are 3 ways to pass arrays as function arguments.

  • 作为指针的形式参数,例如 void myFunction(int * param){}
  • 形式参数为大小数组,例如, void myFunction(int param [10]){}
  • 形式参数为无尺寸数组,例如, void myFunction(int param []){}
  • Formal parameters as a pointer, e.g., void myFunction(int *param) {}
  • Formal parameters as a sized array, e.g., void myFunction(int param[10]) {}
  • Formal parameters as an unsized array, e.g., void myFunction(int param[]) {}

哪种方式在效率和可读性方面更好?

Which way is better in terms of efficiency and readability?

推荐答案

哪种方法最好在C中将数组作为函数参数传递?

Which way is better to pass arrays as function arguments in C?

我要使用 4号门.接收功能需要知道大小.

I am going for Door #4. The receiving function needs to know the size.

void myFunction(size_t array_element_count, int *param);

或者,代码可以使用终止标记,但是没有特殊的"I-am-not-an-int"值.

Alternatively code could use a terminating sentinel, but there are no special "I-am-not-an-int" values.

就以下而言,它们发出相同的代码.这是一个样式问题.因此,请遵循小组的风格指南.对我来说,我更喜欢 size_t array_element_count和int param [array_element_count] 作为代码意图的最有用信息.

In terms of the below, they emit the same code. This is a style issue. As such, follow the group's style guide. For me I favor size_t array_element_count, int param[array_element_count] as most informative to code's intent.

void myFunction(size_t array_element_count, int *param);
void myFunction(size_t array_element_count, int param[array_element_count]);
void myFunction(size_t array_element_count, int param[]);


在样式上, f(size,ptr) f(ptr,size)大小,ptr).具有更复杂的阵列和VLA支持的IAC,以下内容很有用:


In terms of style, f(size, ptr) vs f(ptr, size), I recall reading on the next C rev promoting f(size, ptr). IAC, with more complex arrays and VLA support , the below is useful:

foo(size_t row, size_t col, matrix[row][col]);

这篇关于哪种方法最好在C中将数组作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆