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.
So a string size is 18 + (2 * number of characters) bytes. (In reality, another 2 bytes is sometimes used for packing to ensure 32-bit alignment, but I'll ignore that). 2 bytes is needed for each character, since . NET strings are UTF-16.
You can get the length of a string object by using a size() function or a length() function.
For instance, if a 24-bit image is captured with a digital camera with pixel dimensions of 2,048 x 3,072, then the file size equals (2048 x 3072 x 24)/8, or 18,874,368 bytes.
Use the len() function to get the length of a bytes object, e.g. len(my_bytes) . The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set).
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With