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
sizeofto get its size.
If you are confused about difference between dynamic and static arrays, check this.
Answer from nmikhailov on Stack OverflowYou 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
sizeofto 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.
Calculating length of a string with strlen()
Why is the length of a string in Foreign.C.String defined as Int and not as CSize?
Why and how is size_t type used for storing string length?
Size occupied by C++ string
Videos
Let's say that we have a string char myStr[] = "Hello there!"
The 1st option to calculate the length is
int length = sizeof(myStr)/ sizeof(myStr[0]);
The 2nd option is simply to use the strlen() function, but I'm seeing that it will not count the null terminating character at the end.
My question: Would it be a problem using strlen() in embedded projects since it dosn't include the null terminating character as it's length? Or it's safer to just use the 1st option instead?
I'm thinking as an example of a case when you need to allocate emory, and you're relying on this strlen() function, it will not allocate for the null character, which might lead to problems down the line?
Thanks