Getting wrong string length

前端 未结 3 1524
心在旅途
心在旅途 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题