如果我有一个固定大小的数组取决于它的定义和使用方式,我通常使用两种方法之一来引用它.
数组类型1:由于它是基于定义的固定大小,我只是在引用它的所有循环中使用该定义.
#define MAXPLAYERS 4
int playerscores[MAXPLAYERS];
for(i=0;i<MAXPLAYERS;++i)
{
.... do something with each player
}
Run Code Online (Sandbox Code Playgroud)
数组类型2:由于此数组可以随着项目的添加而增长,因此我使用sizeof来计算其中的条目数.编译器将大小转换为常量,因此不应该以这种方式执行任何运行时惩罚.
typedef struct
{
fields....
}MYSTRUCT_DEF;
MYSTRUCT_DEF mystruct[]={
{entry 1},
{entry 2},
{entry 3...n}
};
for(i=0;i<(sizeof(mystruct)/sizeof(MYSTRUCT_DEF));++i)
{
..... do something with each entry
}
Run Code Online (Sandbox Code Playgroud)
是否有一个更优雅的解决方案来处理数组处理而不会过早结束或过早停止.思考?评论?
无论数组元素类型如何,这都适用于您的两种情况:
#define ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0]))
...
struct foo arr[100];
...
for (i = 0; i < ARRAY_COUNT(arr); ++i) {
/* do stuff to arr[i] */
}
Run Code Online (Sandbox Code Playgroud)
在C++中只需使用vector类.
如果由于某种原因你不能,那么就有你想要的宏实现.请参阅此答案,了解winnt.h中一组在C中工作的宏,在C++中更安全:
使用stdlib.h的_countof宏
// 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
}
Run Code Online (Sandbox Code Playgroud)