On Sun, 14 Nov 2004 00:20:19 -0800, terry wrote:
Hi,
Could anyone tell me how to determine the size of array of characters
dynamically? For example,
:
:
char *a[]={"hello","hi","kitty"};
char *b[]={"orange","apple"};
void main()
In C main returns int.
{
char **p=a;
:
:
}
I want to get array size of "a" which is 3 by "p". How?
In C a pointer doesn't know anything about the size of an array it is
pointing at. This is fundamental and means that even various standard
library functions that need to know the size of an array require you to
pass that size (e.g. fgets()). So the direct answer to your question to
your question is that you can't.
As others have said there are various techniques to work around this, e.g.
putting a marker in the array data or maintaining a size variable
alongside the pointer. And this is an issue specifically with pointers, if
you have the ARRAY definition available you can get the size off that e.g.
(sizeof a/sizeof *a) will evaluate to 3 for the definition of a above.
Lawrence