You can't. A pointer is nothing more or less than an address in memory. A simple number. The start of the array is at a different address in memory, another simple number.
For instance, your array might start at the memory address 12608 (= any possible number except 0), and the last element of it would be at address 12680. You don't know what is stored either at address 12600 or 12688. If you access either of these addresses, anything might happen from silent data corruption, over an immediate crash, up to and including some bad guy downloading a backdoor onto your PC.
As such, it is your job to ensure that your program does not access any arrays out-of-bounds. It is your job to ensure that you know the size and starting address of the array at any point where you need them, and it is your job to ensure that all accesses are within these limits.
Now, for a statically allocated array like the one in your example, you can take its size by using the sizeof
operator:
size_t wordCount = sizeof(words)/sizeof(*words);
printf("this should be 9 in your example: %zu\n", wordCount);
This takes the number of bytes used for the array words
, and divides it by the number of bytes in the first element of the array *words
. It's the standard trick to get the element count of static arrays.
However, that only works as long as words
is actually an array of which the compiler knows the size. Once you pass it to a function, that information is gone:
void buggy(char* words[]) {
printf("not what you expect: %zu\n", sizeof(words)/sizeof(*words));
}
The reason is, that arrays decay into pointers when you pass them to a function, and a pointer is only a single number that does not retain any size information of the array. That information was only in the array's type, and that type has decayed away.