开发者

How to get length of char**?

Quick c question: How to know the length of a cha开发者_StackOverflowr* foo[]?

Thanks.


You can't. Not without knowing something about what is inside of the pointers, or storing that data ahead of time.


You mean the number of strings in the array?

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

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

If you're talking about the argv passed to main, you can look at the argc parameter.

If the array was allocated on the heap or passed into a function (where it would decay into a pointer), you're out of luck unless whoever allocated it passed the size to you as well.


If the array is statically allocated you can use the sizeof() function. So sizeof(foo)/sizeof(char *) would work. If the array was made dynamically, you're in trouble! The length of such an array would normally be explicitly stored.

EDIT: janks is of course right, sizeof is an operator.

Also it's worth pointing out that C99 does allow sizeof on variable-size arrays. However different compilers implement different parts of C99, so some caution is warranted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜