How to get the string size in bytes?
If you use sizeof()
then a char *str
and char str[]
will return different answers. char str[]
will return the length of the string(including the string terminator) while char *str
will return the size of the pointer(differs as per compiler).
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.
Use strlen
to get the length of a null-terminated string.
sizeof
returns the length of the array not the string. If it's a pointer (char *s
), not an array (char s[]
), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof
to check the size of the array.
So, only if the string spans the entire array (e.g. char s[] = "stuff"
), would using sizeof
for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.
An alternative to all this is actually storing the size of the string.
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.