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

前端 未结 9 1411
长发绾君心
长发绾君心 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:39

    What you're defining here isn't literally an array of strings , it's an array of pointers to characters. if you want to know the number of strings, you simply have to count the pointers, so something like

    size_t size = sizeof(names)/sizeof(char*);
    

    would do,this way you're dividing the size of the array by the size of a single pointer.But be aware this only works if the size of the array is known at compile time(i.e. the array is allocated statically), if it's defined dynamically (i.e. char** strings) then sizeof(strings) would return the size of the pointer not the array.

    p.s.:the length of the strings is not relevant, as the array isn't even "aware" of what the pointers point to.

提交回复
热议问题