char * s3 = new char[42]; l3 = strlen(s3); I declared a string of 42 characters long but l3 is 47 What went wrong?
strlen searches for the first character equal to 0 . The number of characters before it is the result of the strlen function. The new operator allocates memory and does not initialize it. Memory is filled with random data. You're lucky the zero byte is so close. Otherwise, you might get a segmentation fault error.
It is not clear which compiler and where is declared. Try this:
char * s3 = new char[42]{0}; int l3 = strlen(s3); The length must be zero.
I announced a string of 42 characters long but l3 is 47 What went wrong?
No, you have never declared a string with a length of 42 characters. In this code snippet
char * s3 = new char[42]; l3 = strlen(s3); You have declared one variable: the variable s3 , which has the pointer type char * . In this code snippet, the string is never used anywhere.
A string is a sequence of characters, bounded by a terminating null, that is, the '\0' character.
The pointer s3 initialized with the address of the first byte of the dynamically allocated memory of 42 bytes. However, the dynamically allocated memory itself is not initialized in any way; therefore, it is meaningless to use the strlen function.
You could initialize the allocated memory with zeros, for example, as follows.
char * s3 = new char[42](); and then this memory at its very beginning would contain an empty string, that is, a string that consists of a single character '\0' .
In this case, the result of applying the strlen function will be 0.
From the description of the strlen function in standard C
The strlen function returns the terminating null character.
When you dynamically allocate memory, you need to store the size of the allocated memory yourself in some variable. For example,
int n = 42; char *str = new char[n]; If you instead of a dynamically allocated character array and declarations of the corresponding pointer, declared an array, for example,
char str[42]; then the sizeof( str ) operator would return the value 42 to you. This operator returns the size of the memory occupied by the array, but, however, it is not suitable for determining the length of a string that can be stored in this array.
For example,
char str[42] = "Hello"; std::cout << sizeof( str ) << std::endl; std::cout << std::strlen( str ) << std::endl; The first of these sentences will infer 42 , while the second is 5 .
The sizeof operator is meaningless to apply to a pointer to dynamically allocated memory, such as
char *str = new char[42]; size_t n = sizeof( str ); because it does not return the size of the allocated dynamic memory, but the size of the pointer itself, which, depending on the system used, may be, for example, 4 or 8.
Source: https://ru.stackoverflow.com/questions/593512/
All Articles