Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C sizeof char* array

Tags:

c

sizeof

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])  
like image 657
Ayman Avatar asked Oct 13 '09 12:10

Ayman


People also ask

What is the size of char * in C?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.

Can you use sizeof on a char *?

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.

Can I use sizeof on a char array?

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.

How do I find the size of a char pointer array?

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.


1 Answers

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.

like image 73
sharptooth Avatar answered Oct 16 '22 14:10

sharptooth