Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get length of char**?

Tags:

arrays

c

Quick c question: How to know the length of a char* foo[]?

Thanks.

like image 326
nunos Avatar asked Apr 08 '10 16:04

nunos


3 Answers

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

like image 132
Robert P Avatar answered Sep 28 '22 07:09

Robert P


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.

like image 24
Nick Meyer Avatar answered Sep 28 '22 08:09

Nick Meyer


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.

like image 27
Yuvi Masory Avatar answered Sep 28 '22 06:09

Yuvi Masory