有个A函数,声明为
void A(stB b[]);
其中stB为一个结构类型A的调用为
...
stB c[5];
A(c);
...那么在A中,获得b的元素个数是sizeof(b) + 1 还是 sizeof(b) / sizeof(stB) ? 

解决方案 »

  1.   

    都不是,数组进函数,自动退化为指针,所以你必须指定一个数组的大小座位参数传进去。
    但是如果在函数外面调用获得数组元素个数的方法就是sizeof(b)/sizeof(stB)
      

  2.   


    但是我发现sizeof(b) 正好等于我传进去的数组的最大下标,这个怎么解释呢?
      

  3.   

    sizeof跟元素个数有什么关系?
      

  4.   

    sizof 求的的是字节数 不是 sizeof(b)/sizeof(b[0])(你这个求的是字节数!!!)
    比如sizeof(int) 返回是4,因为int占4个字节.
    sizeof(b)/sizeof(b[0])求的是数组元素个数
    MSDN// crt_countof.cpp
    #define _UNICODE
    #include <stdio.h>
    #include <stdlib.h>
    #include <tchar.h>
    [code]
    // crt_countof.cpp
    #define _UNICODE
    #include <stdio.h>
    #include <stdlib.h>
    #include <tchar.h>int main( void )
    {
       _TCHAR arr[20], *p;
       printf( "sizeof(arr) = %d bytes\n", sizeof(arr) );
       printf( "_countof(arr) = %d elements\n", _countof(arr) );
       // In C++, the following line would generate a compile-time error:
       // printf( "%d\n", _countof(p) ); // error C2784 (because p is a pointer)   _tcscpy_s( arr, _countof(arr), _T("a string") );
       // unlike sizeof, _countof works here for both narrow- and wide-character strings
    }
     
      Copy Code 
    sizeof(arr) = 40 bytes
    _countof(arr) = 20 elements
     
    [/code]
      

  5.   


    // crt_countof.cpp
    #define _UNICODE
    #include <stdio.h>
    #include <stdlib.h>
    #include <tchar.h>int main( void )
    {
       _TCHAR arr[20], *p;
       printf( "sizeof(arr) = %d bytes\n", sizeof(arr) );
       printf( "_countof(arr) = %d elements\n", _countof(arr) );
       // In C++, the following line would generate a compile-time error:
       // printf( "%d\n", _countof(p) ); // error C2784 (because p is a pointer)   _tcscpy_s( arr, _countof(arr), _T("a string") );
       // unlike sizeof, _countof works here for both narrow- and wide-character strings
    }
     
    sizeof(arr) = 40 bytes
    _countof(arr) = 20 elements
     
      

  6.   

    上面字打错了/..
    sizeof(b)/sizeof(b[0])(你这个求的是元素个数!!!)
      

  7.   

    对,刚才又做了下实验,的确,是个巧合~~
    正好传了5个元素进去,sizeof一下等于4,其实这个4应该是一个long ptr的大小,居然那么巧