How to get the string size in bytes?
arrays, c, sizeof
Solution
You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.
If you want to get size of memory buffer, that contains your string, and you have pointer to it:
- If it is dynamic array(created with malloc), it is impossible to get it size, since compiler doesn't know what pointer is pointing at. (check this)
- If it is static array, you can use `sizeof` to get its size.
If you are confused about difference between dynamic and static arrays, check this.
Problem
As the title implies, my question is how to get the size of a string in `C`. Is it good to use `sizeof` if I've declared it (the string) in a function without `malloc` in it? Or, if I've declared it as a pointer? What if I initialized it with `malloc`? I would like to have an exhaustive response.