代码之家  ›  专栏  ›  技术社区  ›  unj2

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

  •  8
  • unj2  · 技术社区  · 14 年前

    我正在尝试编写一个函数来打印数组中的元素。但是,当我处理传递的数组时,我不知道如何迭代该数组。

    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]);
        }
    }
    

    迭代传递的数组的最佳方法是什么?

    6 回复  |  直到 12 年前
        1
  •  16
  •   Brian R. Bondy    14 年前


    (b+1) b[1]

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

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

    arrays are not the same as pointers

        2
  •  5
  •   Chubsdad    14 年前

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

        3
  •  2
  •   Arun    12 年前

    std::array here here at()

        4
  •  0
  •   Matt Joiner    14 年前

    C99 n

    void print_array(int b[static n]);
    

    6.7.5.3.7

    pass the size of an array implicitly

    void print_array(int n, int b[n]);
    
        5
  •  0
  •   Tony Delroy    14 年前

    #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);                                                             
    }
    

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

        6
  •  0
  •   Roman A. Taycher    14 年前