I want to find the length of this :
char *s[]={\"s\",\"a\",\"b\"};
it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives
What you have defined is not a string hence there is no NULL terminating character. Here you have declared pointers to 3 separate strings. BTW, you should declare your array as const char*
.
strlen works if you terminate your array with null character. You cannot find number of elements in a char array unless you keep track of it. i.e store it in some variable like n. Every time you add member increment n and every time you remove decrement n
You are making an array of char*
and not of char
. That's why strlen
won't work. Use
sizeof(s) / sizeof(char*) //should give 3
If you want a single string use
char s[] = "sab";
There is no direct way to determine the length of an array in C. Arrays in C are represented by a continuous block in a memory.
You must keep the length of the array as a separate value.
Why should it count 4? you have 3 pointers to char in this array, it should count 12 on most 32-bit platforms.
sizeof(s) / sizeof(s[0])
works no matter what type s
contains.