Home c Determining the length of a string in C and C++

Determining the length of a string in C and C++

Author

Date

Category

What is the difference between the following two entries?

len1 = sizeof (buffer);
len2 = strlen (buffer);

Answer 1, authority 100%

The main difference is that strlen calculates the length of the string, and sizeof has nothing to do with calculating the length of the string. The sizeof operator is used to determine the amount of memory occupied by an entity. When working with strings, it can only be applied to strings defined on the stack and constant strings. The mechanism of work can be seen on the example:

char * pStr = "string";
char str [20];
strcpy (str, pStr);
int len1 = strlen (pStr); // = 6
int len2 = strlen (str); // = 6
int len3 = sizeof (pStr); // = 4 if 32-bit system is used
int len4 = sizeof (str); // = 20
int len5 = sizeof ("string"); // = 7

Answer 2, authority 75%

sizeof is a language operator used to determine the size of a data type in bytes. The value of an expression using sizeof is determined at compile time, except in some cases, such as for variable length arrays defined in C99.


Answer 3, authority 38%

Note that sizeof returns the size of the object in bytes. Those. usually this is the maximum length of a string that fits into a char array.

strlen is a standard library function for determining the length of a 0-terminated string.
Returns the number of characters without a terminating zero. the actual size of a string in memory is at least the result of strlen + 1 byte.

In reality, problems usually arise when working with Unicode, i.e. with types wchar or TCHAR and corresponding functions. Because Unicode characters occupy not 1 byte, but 2. And therefore, mixing the number of characters and their size in memory, it turns out, is no longer worth it. And given that many programs will have to be redone sooner or later, it is better to immediately lay the opportunity for this. Those. total – remember that the functions for working with strings usually require the size (or maximum size) of the string in characters, and the functions for working with memory – usually in bytes.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions