简体   繁体   English

你如何获得传递给 function 的数组的大小?

[英]How do you get the size of array that is passed into the function?

I am trying to write a function that prints out the elements in an array.我正在尝试编写一个 function 来打印出数组中的元素。 However when I work with the arrays that are passed, I don't know how to iterate over the array.但是,当我使用传递的 arrays 时,我不知道如何遍历数组。

void
print_array(int* b)
{
  int sizeof_b = sizeof(b) / sizeof(b[0]);
  int i;
  for (i = 0; i < sizeof_b; i++)
    {
      printf("%d", b[i]);
    }
}

What is the best way to do iterate over the passed array?迭代传递的数组的最佳方法是什么?

You need to also pass the size of the array to the function.您还需要将数组的大小传递给函数。
When you pass in the array to your function, you are really passing in the address of the first element in that array.当您将数组传递给函数时,您实际上是在传递该数组中第一个元素的地址。 So the pointer is only pointing to the first element once inside your function.所以指针只指向函数内部的第一个元素。

Since memory in the array is continuous though, you can still use pointer arithmetic such as (b+1) to point to the second element or equivalently b[1]由于数组中的内存是连续的,您仍然可以使用指针算法,例如(b+1)指向第二个元素或等效地b[1]

void print_array(int* b, int num_elements)
{
  for (int i = 0; i < num_elements; i++)
    {
      printf("%d", b[i]);
    }
}

This trick only works with arrays not pointers:这个技巧只适用于数组而不是指针:

sizeof(b) / sizeof(b[0])

... and arrays are not the same as pointers . ...和数组与指针不同

Why don't you use function templates for this (C++)?为什么不为此(C++)使用函数模板?

template<class T, int N> void f(T (&r)[N]){
}

int main(){
    int buf[10];
    f(buf);
}

EDIT 2:编辑2:

The qn now appears to have C tag and the C++ tag is removed. qn 现在似乎具有 C 标记,而 C++ 标记已被删除。

For C, you have to pass the length (number of elements)of the array.对于 C,您必须传递数组的长度(元素数)。

For C++, you can pass the length, BUT, if you have access to C++0x, BETTER is to use std::array .对于 C++,您可以传递长度,但是,如果您可以访问 C++0x,最好使用std::array See here and here .请参阅此处此处 It carries the length, and provides check for out-of-bound if you access elements using the at() member function.它携带长度,并在您使用at()成员函数访问元素时提供越界检查。

You could try this...你可以试试这个...

#include <cstdio>                                                               

void 
print_array(int b[], size_t N) 
{ 
    for (int i = 0; i < N; ++i) 
        printf("%d ", b[i]);
    printf("\n");
}

template <size_t N>
inline void 
print_array(int (&b)[N]) 
{
    // could have loop here, but inline forwarding to
    // single function eliminates code bloat...
    print_array(b, N);
}                                                                                

int main()                                                                      
{                                                                               
    int a[] = { 1, 2 };                                                         
    int b[] = { };
    int c[] = { 1, 2, 3, 4, 5 };                                                

    print_array(a);                                                             
    // print_array(b);                                                          
    print_array(c);                                                             
}

...interestingly b doesn't work... ...有趣的是 b 不起作用...

array_size.cc: In function `int main()':
array_size.cc:19: error: no matching function for call to `print_array(int[0u])'

JoshD points out in comments below the issue re 0 sized arrays (a GCC extension), and the size inference above. JoshD 在问题下方的评论中指出了 0 大小的数组(GCC 扩展),以及上面的大小推断。

In C99 , you can require that an array an array has at least n elements thusly:C99 中,你可以要求一个数组至少有n元素:

void print_array(int b[static n]);

6.7.5.3.7 : A declaration of a parameter as ''array of type'' shall be adjusted to ''qualified pointer to type'', where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. 6.7.5.3.7 :将参数声明为“类型数组”应调整为“类型限定指针”,其中类型限定符(如果有)是在 [ 和 ] 中指定的那些数组类型推导。 If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.如果关键字 static 也出现在数组类型派生的 [ 和 ] 中,那么对于函数的每次调用,相应实参的值应提供对数组的第一个元素的访问,该元素至少与指定的元素一样多由大小表达式。

In GCC you can pass the size of an array implicitly like this:在 GCC 中,您可以像这样隐式传递数组的大小

void print_array(int n, int b[n]);

在 c++ 中,您还可以使用某种类型的列表类,该类实现为具有 size 方法的数组或具有 size 成员的结构(在 c 或 c++ 中)。

Use variable to pass the size of array.使用变量传递数组的大小。 int sizeof_b = sizeof(b) / sizeof(b[0]); does nothing but getting the pre-declared array size, which is known, and you could have passed it as an argument;除了获取预先声明的数组大小之外什么都不做,这是已知的,您可以将其作为参数传递; for instance, void print_array(int*b, int size) .例如, void print_array(int*b, int size) size could be the user-defined size too. size也可以是用户定义的大小。

int sizeof_b = sizeof(b) / sizeof(b[0]); will cause redundant iteration when the number of elements is less than the pre-declared array-size.当元素数量小于预先声明的数组大小时,将导致冗余迭代。

The question has already some good answers, for example the second one .这个问题已经有了一些很好的答案,例如第二个 However there is a lack of explanation so I would like to extend the sample and explain it:然而,缺乏解释,所以我想扩展样本并解释它:

Using template and template parameters and in this case None-Type Template parameters makes it possible to get the size of a fixed array with any type.使用模板和模板参数,在这种情况下,使用无类型模板参数可以获取任何类型的固定数组的大小。

Assume you have such a function template:假设您有这样一个函数模板:

template<typename T, int S>
int getSizeOfArray(T (&arr)[S]) {
    return S;
}

The template is clearly for any type(here T) and a fixed integer(S).该模板显然适用于任何类型(此处为 T)和固定整数(S)。 The function as you see takes a reference to an array of S objects of type T , as you know in C++ you cannot pass arrays to functions by value but by reference so the function has to take a reference.如您所见,该函数引用了对 T 类型的 S 对象数组的引用,正如您在 C++ 中所知,您不能通过值将数组传递给函数,而是通过引用将数组传递给函数,因此该函数必须引用。

Now if u use it like this:现在,如果你像这样使用它:

int i_arr[] = { 3, 8, 90, -1 };
std::cout << "number f elements in Array: " << getSizeOfArray(i_arr) << std::endl;

The compiler will implicitly instantiate the template function and detect the arguments, so the S here is 4 which is returned and printed to output.编译器会隐式实例化模板函数并检测参数,所以这里的 S 是4 ,它被返回并打印到输出。

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

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