find the number of strings in an array of strings in C

前端 未结 9 1429
长发绾君心
长发绾君心 2020-12-13 18:00
char* names[]={\"A\", \"B\", \"C\"};

Is there a way to find the number of strings in the array. Like, for example in this case, it has to be 3. Ple

9条回答
  •  鱼传尺愫
    2020-12-13 18:25

    Is there a way to find the number of strings in the array

    Of course there is, try this:

    #include
    
    int main(void){
        size_t size, i=0;
        int count=0;
        char* names[]={"A", "B", "C"};
    
        size = sizeof(names)/sizeof(char*);
    
        for(i=0;i
    1 - A
    2 - B
    3 - C
    
    The number of strings found are 3
    

    Same thing with:

    #include
    
    int main(void){
        size_t size, i=0;
        int count=0;
        char *names[]={"Jimmy", "Tom", "Michael", "Maria", "Sandra", "Madonna"};
    
        size = sizeof(names)/sizeof(char*);
    
        for(i=0;i

    Output:

    1 - Jimmy
    2 - Tom
    3 - Michael
    4 - Maria
    5 - Sandra
    6 - Madonna
    
    The number of strings found are 6
    

    Or use a Function like this:

    #include
    
    size_t arrLength(size_t len, char **arr){
        size_t i=0;
        size_t count=0;
    
        for(i=0;i

    Output:

    1 - Jimmy
    2 - Tom
    3 - Michael
    4 - Maria
    5 - Sandra
    6 - Madonna
    
    The number of strings found are 6
    

提交回复
热议问题