C: finding the number of elements in an array[]

前端 未结 11 1848
陌清茗
陌清茗 2020-12-16 14:31

In C: How do you find the number of elements in an array of structs, after sending it to a function?

int main(void) {
  myStruct array[] = { struct1, struct2         


        
11条回答
  •  别那么骄傲
    2020-12-16 15:01

    You may use a format for your array. I am using string elements, it should work for struct.

    #define NULL ""
    #define SAME 0
    
    static char *check[] = {
          "des", "md5", "des3_ede", "rot13", "sha1", "sha224", "sha256",
          "blowfish", "twofish", "serpent", "sha384", "sha512", "md4", "aes",
          "cast6", "arc4", "michael_mic", "deflate", "crc32c", "tea", "xtea",
          "khazad", "wp512", "wp384", "wp256", "tnepres", "xeta",  "fcrypt",
          "camellia", "seed", "salsa20", "rmd128", "rmd160", "rmd256", "rmd320",
          "lzo", "cts", "zlib", NULL
     }; // 38 items, excluding NULL
    

    in main ( )

    char **algo = check;
    int numberOfAlgo = 0;
    
    
    while (SAME != strcmp(algo[numberOfAlgo], NULL)) {
        printf("Algo: %s \n", algo[numberOfAlgo++]);
    }
    
    printf("There are %d algos in the check list. \n", numberOfAlgo);
    

    You should get the output:

    Algo: des 
       :
       :
    Algo: zlib 
    
    There are 38 algos in the check list.
    

    Alternatively, if you do not want to use the NULL , do this instead:

    numberOfAlgo = 0;
    
    while (*algo) {
        printf("Algo: %s \n", *algo);
        algo++;         // go to the next item
        numberOfAlgo++; // count the item
    }
    
    printf("There are %d algos in the check list. \n", numberOfAlgo);
    

提交回复
热议问题