阵传球达阵之间的差别,固定大小的数组和基地址作为函数参数 [英] Difference between passing array, fixed-sized array and base address of array as a function parameter
问题描述
我感到困惑,如果我想通过已知或未知大小的数组作为函数参数要使用的语法。
I am confused about which syntax to use if I want to pass an array of known or unknown size as a function parameter.
假设我有目的有以下变种:
Suppose I have these variants for the purpose:
void func1(char* str) {
//print str
}
void func2(char str[]) {
//print str
}
void func3(char str[10]) {
//print str
}
什么是使用这些每个人的优点和缺点是什么?
What are the pros and cons of using each one of these?
推荐答案
所有这些变体是相同的。 ç只是让你使用的拼写方式,但即使有一个数组大小注解明确的最后一个变量衰变到一个正常的指针。
All these variants are the same. C just lets you use alternative spellings but even the last variant explicitly annotated with an array size decays to a normal pointer.
也就是说,即使最后执行,你可以调用该函数与数组的任何的尺寸:
That is, even with the last implementation you could call the function with an array of any size:
void func3(char str[10]) { }
func("test"); // Works.
func("let's try something longer"); // Not a single f*ck given.
不用说,这应该的不的使用:它可能给用户安全的错觉(哦,这个功能只接受长度为10的数组,所以我并不需要检查长度自己)。
Needless to say this should not be used: it might give the user a false sense of security ("oh, this function only accepts an array of length 10 so I don’t need to check the length myself").
由于亨里克说,正确的方法的在C ++ 的是使用的std :: string的
,的std :: string的&放;
或的std :: string的常量和放大器;
(取决于你是否需要修改的对象,以及是否要复制)
As Henrik said, the correct way in C++ is to use std::string
, std::string&
or std::string const&
(depending on whether you need to modify the object, and whether you want to copy).
这篇关于阵传球达阵之间的差别,固定大小的数组和基地址作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!