How to get the real and total length of char * (char array)?

前端 未结 15 2526
小蘑菇
小蘑菇 2020-11-29 00:37

For a char [], I can easily get its length by:

char a[] = \"aaaaa\";
int length = sizeof(a)/sizeof(char); // length=6

However,

15条回答
  •  旧时难觅i
    2020-11-29 01:19

    There are only two ways:

    • If the memory pointer to by your char * represents a C string (that is, it contains characters that have a 0-byte to mark its end), you can use strlen(a).

    • Otherwise, you need to store the length somewhere. Actually, the pointer only points to one char. But we can treat it as if it points to the first element of an array. Since the "length" of that array isn't known you need to store that information somewhere.

提交回复
热议问题