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])
Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.
The sizeof operator returns the size of a type. The operand of sizeof can either be the parenthesized name of a type or an expression but in any case, the size is determined from the type of the operand only. sizeof s1 is thus stricly equivalent to sizeof (char[20]) and returns 20.
first, the char variable is defined in charType and the char array in arr. Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.
Use the sizeof Operator to Find Length of Char Array Then sizes of both arrays are retrieved using the sizeof operator and printed to the console. Note that the second array size is equal to 18 bytes even though there are only 17 printed elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With