数组名称和字符串作为参数传递

huangapple go评论54阅读模式
英文:

Array names and strings are passed as parameters

问题

当函数传递参数时,数组需要传递数组名称和数组长度,但当传递字符串时,不需要传递长度。为什么?

英文:

When a function passes parameters, the array needs to pass the array name and array length, but when passing a string, it does not need to pass the length. Why?

答案1

得分: 2

因为std::string是一个类类型,它存储(跟踪)字符串的长度等状态信息。因此,在这里不需要单独传递字符串的长度。用户可以在调用的函数内使用std::string::size成员函数来访问字符串的长度。


另一方面,数组是内置类型,并不在数组对象内部存储数组的长度。因此,当将数组按值传递给函数时,我们需要单独传递数组的长度作为参数。

请注意,也可以将数组按引用传递给函数,并且甚至可以创建一个接受任意数组的函数模板,以便调用者不必显式传递数组的长度。

英文:

Because std::string is a class-type and it stores(keeps track of) state information like length of the string. So there is no need to pass the length of the string separately here. The user can access the length of the string inside the called function using the std::string::size member function.


On the other hand, arrays are built in types and do not store the length of a given array inside an array object. Thus when passing an array by value to a function, we need to separately pass the length of the array as argument.

Note that it is also possible to pass an array by reference, to a function and we can even create a function template that takes an arbitrary array by reference so that the caller will not have to explicitly pass the length of the array.

答案2

得分: 1

我想你是指传递C字符串、以null结尾的字符串和其他数组之间的差异。

首先,当数组传递给函数时,它们会衰减为指向第一个元素的指针。因此,我们正在比较:

void foo(char* s);
void bar(int* a, size_t size);

正如名称"null terminated string"所示,字符串的最后一个元素是\0\0不是可打印字符,其作用是表示字符串的最后一个元素。

对于其他类型的数组,没有这样的约定。没有任何值可以明显选择为哨兵值。如果0表示整数数组的最后一个元素,那么您将无法在任何其他位置使用带有0的整数数组(好吧,您可以,但会带来重大复杂性和不便)。

在C++中,几乎不需要分别传递数组和大小。有std::stringstd::vectorstd::array。它们的大小可以通过size()来查询。

英文:

I suppose you mean the difference between passing a c-string, a null terminated string, and other arrays.

First of all, arrays decay to pointers to first element when passed to a function. So we are comparing:

   void foo(char* s);
   void bar(int* a, size_t size);

As the name, "null terminated string", suggests there is a \0 as last element in string. \0 is not a printable character, its purpose is to denote the last element of a string.

For arrays of other type there is no such convention. There is no value that would make an obvious choice as sentinel. If 0 would denote the last element in an integer array you would not be able to use integer arrays with a 0 in any other postition (well, you could but with major complications and inconvenience).


In c++ you almost never have to pass an array and size seperately. There is std::string, std::vector, and std::array. Their size can be queried via size().

huangapple
  • 本文由 发表于 2023年3月15日 19:52:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定