tags:

views:

563

answers:

3

I have a char* array as follows:

char *tbl[] = { "1", "2", "3" };

How do I use the sizeof operator to get the number of elements of the array, here 3?

The below did work, but is it correct?

int n = sizeof(tbl) / sizeof(tbl[0])
+5  A: 

Yes,

int n = sizeof(tbl) / sizeof(tbl[0])

is the most typical way to do this.

sharptooth
Anything wrong with using a `size_t` for sizes? Or at least something unsigned?
Chris Lutz
+2  A: 

This was actually answered here

And that was the correct way of doing it.

Ayman
A: 

The shorter and, arguably, cleaner version would look as

sizeof tbl / sizeof *tbl

:)

AndreyT