c does not contain any null characters. How does ptr get the length?
It doesn't. It appears to give the correct answer in your tests because the memory location following the address of c
happens to contain a zero byte. This location is not defined to contain a zero, nor is the program allowed to access it, so you cannot count on such code continuing to work.
In the language of the C standard, the behavior of the program is undefined, which means that not only is the result of the operation unpredictable, the entire program is rendered meaningless.
Even without taking into account undefined behavior, the above code can stop working with the slightest change - for example, when you change architecture, compiler, or even compilation flags, or when you add more functions into the mix. While such code snippets can be useful to learn how stuff works under the hood, they should never be used in production code.