[英]What is the difference between declaring an char pointer and an array of chars in a function parameter list?
What is the difference between 之间有什么区别
foo(char* grid){}
And 和
foo(char grid[]){}
I have a program that I tested on both styles of the function parameters. 我有一个在两种功能参数样式上都经过测试的程序。 It seemed to work, but why does it work?
它似乎有效,但是为什么有效? What is the difference?
有什么区别? Which one is more efficient, and is the first one passing by reference?
哪个效率更高,第一个是通过引用吗?
In the case of a function parameter (and only in that case), they mean the same thing. 对于函数参数(且仅在这种情况下),它们的含义相同。
Note that C99 dropped the "implicit int
" rule, so your examples should be something like: 请注意,C99删除了“ implicit
int
”规则,因此您的示例应类似于:
void foo(char* grid){}
and 和
void foo(char grid[]){}
A parameter defined with an array type is "adjusted" to become a parameter of pointer type, pointing to the the element type of the array. 使用数组类型定义的参数被“调整”为指针类型的参数,指向数组的元素类型。
Reference: N1570 6.7.6.3 paragraph 7. (This is a freely available draft of the 2011 ISO C standard, PDF, 1.7 MB.) 参考: N1570 6.7.6.3第7段。(这是2011 ISO C标准的免费提供的草案,PDF,1.7 MB。)
(In all other contexts, a pointer declaration and an array declaration are different. See section 6 of the comp.lang.c FAQ . (在所有其他上下文中,指针声明和数组声明是不同的。请参见comp.lang.c FAQ的第6节。
All parameters in C are passed by value, not by reference. C中的所有参数都是通过值而不是通过引用传递的。 In this case, the value being passed happens to be a pointer value, which is the address of a
char
object. 在这种情况下,传递的值碰巧是一个指针值,它是
char
对象的地址。 For example, if you write: 例如,如果您编写:
char arr[10];
func(arr);
then the value being passed is &arr[0]
(there's a separate language rule that says that array expressions are converted/adjusted to become pointer expressions in most but not all contexts). 那么传递的值是
&arr[0]
(有一条单独的语言规则,该规则说数组表达式在大多数(但不是全部)上下文中都已转换/调整为指针表达式)。 Note that no information about the length of the array is passed; 注意,没有传递有关数组长度的信息。 if you want to keep track of that, you'll have to do so explicitly.
如果您想跟踪它,则必须明确地这样做。
C doesn't have pass-by-reference as a language feature. C没有通过引用作为语言功能。 Passing a pointer value is a way to emulate pass-by-reference.
传递指针值是一种模拟按引用传递的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.