Even better than
int len = sizeof(buffData) / sizeof(char);
you can write more generally:
int len = sizeof(buffData) / sizeof(buffData[0]);
which will still work if you (or someone else) change the declaration of buffData
, e.g:
double buffData[256];
If you want to know how many actually elements are in the array at some moment in time, there are at least 2 options:
keep track of elements count, each time you insert element increment the counter, decrement on element removal
char buffData[256];
int buffData_n = 0;
buffData[0] = 0x32;
buffData_n++;
memset memory to zero, or zero-initialize it, so then you can count non-zero elements explicitly:
int i = 0;
for ( ; i < 256 && buffData[i]; i++);
printf("There is %d elements in the array now
", i);
If you want to allow for gaps filled by 0, and you can specify the size of a gap:
int n = 0, i = 0;
// gap size 2 max
for ( ; i < 255; i++)
{
if (buffData[i]==0 && buffData[i+1]==0) break;
if (buffData[i]) n++;
}
printf("There is %d elements in the array now
", n);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…