How to find char array length in c

I want to find the length of this:

char *s[]={"s","a","b"}; 

it should read 4 with / 0, but strlen or sizeof (s) / sizeof (char) gives me the wrong answers .. How can I find it?

+6
source share
6 answers

You are creating a char* array, not a char . This is why strlen will not work. Use

 sizeof(s) / sizeof(char*) //should give 3 

If you want one line to use

 char s[] = "sab"; 
+8
source

sizeof(s) / sizeof(s[0]) works regardless of type s .

+6
source

What you defined is not a string, so there is no NULL character. Here you have pointers to 3 separate lines. BTW, you must declare your array as const char* .

+3
source

strlen works if you end your array with a null character. You cannot find the number of elements in a char array unless you track it. those. save it in some variable, for example n. Every time you add increment of member n and every time you remove decrement n

+1
source

There is no direct way to determine the length of an array in C. Arrays in C are represented by a continuous block in memory.

You must save the length of the array as a separate value.

+1
source

Why should he count 4? you have 3 char pointers in this array, it should count 12 on most 32-bit platforms.

0
source

Source: https://habr.com/ru/post/888103/


All Articles