Getting wrong string length

前端 未结 3 1554
心在旅途
心在旅途 2021-01-26 18:00

I am trying to get the length of a string but i am getting the wrong value, it is saying that it is only 4 characters long. Why is this? am i using sizeof() correc

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-26 18:28

    In addition to strlen(), you can assign string literal to array of chars char s[] = "hello world", in this case sizeof() returns size of array in bytes. In this particular case 12, one extra byte for \0 character at the end of the string.

    Runtime complexity of sizeof() is O(1).

    Complexity of strlen() is O(n).

提交回复
热议问题