Getting wrong string length

前端 未结 3 1512
心在旅途
心在旅途 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:19

    You have declared s as a pointer. When applied to a pointer, sizeof() returns the size of the pointer, not the size of the element pointed to. On your system, the size of a pointer to char happens to be four bytes. So you will see 4 as your output.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-26 18:31

    The sizeof operator is returning the size of the pointer. If you want the length of a string, use the strlen function.

    Even if you had an array (e.g. char s[] = "hello world") the sizeof operator would return the wrong value, as it would return the length of the array which includes the string terminator character.

    Oh and as a side note, if you want a string pointer to point to literal string, you should declare it const char *, as string literals are constant and can't be modified.

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