(转)sizeof()和_countof()区别 - 榕树下的愿望 - 博客园

PHOTO EMBED

Fri Dec 09 2022 00:45:05 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#include <iostream>

using namespace std;

int main(int argc, char* argv[])

{

    char *a = "abcde";

    char sz1[] = "abc";

    char sz2[] = {"abc"};

    char sz3[] = { 'a', 'b', 'c' };

 

    printf_s( "%d %d %d %d", _sizeof(a), _countof(sz1), _countof(sz2), _countof(sz3) );

    cout<<endl;

 

    int b[] = {1,2,3};

    cout<<sizeof(b)<<" "<<_countof(b)<<endl;

    return 0;

}

程序输出:4 4 4 3

                 12    3

//***************************************************************************//

_countof 是 C++中计算一个固定大小数组长度的宏,比如:

T arr[10];

for( size_t i = 0; i<_countof(arr); --i )   do_something();

// 对于固定大小数组计算起来非常方便。

/* _countof helper */
#if !defined(_countof)
#if !defined(__cplusplus)
#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))
#else
extern "C++"
{
template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) sizeof(*__countof_helper(_Array))
}
#endif
#endif
content_copyCOPY

https://www.cnblogs.com/qijicxl/p/3614421.html