Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how to find actual end of char array in c containing zeros in the middle

I am trying to find size of char array in c. There are zeros in between, so strlen does not give the right answer. An example scenario is below.

char buffData[256];
buffData[0] = 0x89;
buffData[1] = 0x32;
buffData[2] = 0x00;
buffData[3] = 0x02;
buffData[4] = 0x01;

How can I find the right length. ps: strlen would give 2 which is wrong

I want the answer 5 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. 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++;
    
  2. 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...