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])
Yes,
size_t n = sizeof(tbl) / sizeof(tbl[0])
is the most typical way to do this.
Please note that using int for array sizes is not the best idea.
size_t for sizes? Or at least something unsigned?sizeof(char) doesn't save you a dereferencing operation. The compiler calculates size of tbl[0] by understanding its type, and doesn't actually generate code for it. The only thing sizeof(char) instead of sizeof(tbl[0]) would achieve for you is problem in the future if the array changes its type from char to something else.sizeof being called for a variable size array, it might optimize it to "multiply array length by element size" which will result in "almost compile time" sizeof. There is no thing called "array" in run time and thus there is nowhere to store its size.int array[n]; length = sizeof(array) / sizeof(*array); we can assume that length = n; and avoid any computations at all.sizeof(tbl[0]) by sizeof(char) is not an optimization -- nor is it correct. tbl[0] is a char*, not a char (and sizeof(char) is 1 by definition), so your "optimized" version simply yields the size in bytes of the array. sizeof is always evaluated at compile time unless the argument is a variable-length array.Yes, it will give you the number of elements in the array tb1.
int n = sizeof(tbl) / sizeof(tbl[0])
Interpretation:
sizeof(tb1) will gives the size of the entire array i.e, tb1 = 3 bytes
sizeof(tb1[0]) gives the size of the character as tb1[0] gives a character value(value at address tb1+0) = 1 byte
Division of those two will give you 3 elements
tbl is an array of char*, not an array of char. If sizeof (char*) == 4, then you're dividing 12 bytes by 4 bytes, yield 3 array elements, not 3 bytes.tbl is an array of char*, not an array of char. The size of tbl[0] isn't 1 byte unless you're on a weird system with 1-byte pointers.
char *tbl[]is really of typechar**; the type is adjusted at compile time.