Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the string size in bytes?

Tags:

arrays

c

sizeof

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.

like image 899
artaxerxe Avatar asked Feb 21 '13 11:02

artaxerxe


People also ask

How do you calculate string size in bytes?

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.

How do you get a size of a string?

You can get the length of a string object by using a size() function or a length() function.

How do you calculate byte size?

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.

How do you find the byte size of a string in Python?

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).


2 Answers

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.

like image 166
nmikhailov Avatar answered Sep 23 '22 18:09

nmikhailov


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.

like image 32
Bernhard Barker Avatar answered Sep 22 '22 18:09

Bernhard Barker