How to get char ** length?

Quick question c: How do I know the length of char * foo []?

Thank.

+5
source share
3 answers

You can not. Not knowing something about what is inside the pointers, or storing this data ahead of time.

+11
source

Do you mean the number of rows in the array?

If the array was allocated on the stack in the same block, you can use the trick sizeof(foo)/sizeof(foo[0]).

const char *foo[] = { "abc", "def" };
const size_t length = sizeof(foo)/sizeof(foo[0]);

If you are talking about argvtransferred to the main, you can look at the parameter argc.

If the array was allocated on the heap or passed to the function (where it will decay to a pointer), you are out of luck, unless someone passed the size to you.

+6
source

, sizeof(). sizeof(foo)/sizeof(char *) . , ! .

EDIT: janks, of course, is right, the sizeofoperator.

It is also worth noting that C99 allows sizeoffor arrays of variable size. However, different compilers implement different parts of C99, so care must be taken.

+2
source

All Articles