How to find the length of an char array in c

后端 未结 6 1183
野性不改
野性不改 2021-02-06 12:06

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

相关标签:
6条回答
  • 2021-02-06 12:26

    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*.

    0 讨论(0)
  • 2021-02-06 12:28

    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

    0 讨论(0)
  • 2021-02-06 12:43

    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";
    
    0 讨论(0)
  • 2021-02-06 12:44

    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.

    0 讨论(0)
  • 2021-02-06 12:48

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

    0 讨论(0)
  • 2021-02-06 12:51

    sizeof(s) / sizeof(s[0]) works no matter what type s contains.

    0 讨论(0)
提交回复
热议问题