Chartmp1[ -] = {"Hello , hi."}; CharTmp2[] = {"Hello , hi."}; Char*tmp3 =New Char[ -]; sprintf (Tmp3,"%s","Hello , hi."); stringTmp4 ="Hello , hi."; printf ("%d %d%d%d\n",sizeof(TMP1),sizeof(TMP2),sizeof(Tmp3),sizeof(Tmp4)); printf ("%d %d%d%d%d\n", strlen (TMP1), strlen (TMP2), strlen (Tmp3), strlen (Tmp4.c_str ()), tmp4.size ());
Output:
20 13 4 4
12 12 12) 12 12
Explain:
At compile time, the TMP1 array is assigned 20 bytes; TMP2 allocates the minimum capacity based on the initialization content, including the end of the string ' \ s ', so the 13;tmp3 is only a pointer variable at compile time, only 4 bytes in size;
The contents of the string object use pointers to dynamically allocated space, and the object itself is only 4 bytes.
The difference and connection between sizeof and strlen
First, sizeof
sizeof (...) is an operator, the typedef in the header file is unsigned int, and its value is calculated at compile time, and the parameters can be arrays, pointers, types, objects, functions, and so on.
Its function is to ensure that the size of the byte that implements the largest object being built is guaranteed to be accommodated.
because it is evaluated at compile time, sizeof cannot be used to return the size of the dynamically allocated memory space. in fact, using sizeof to return a type and the space occupied by statically allocated objects, structures, or arrays, the return value is not related to what the object, structure, or array stores.
Specifically, when the parameters are as follows, the value returned by sizeof represents the following meanings:
Array-the size of the array space allocated at compile time;
Pointer-The amount of space used to store the pointer (the length of the address where the pointer is stored is a long integer, which should be 4);
Type-the amount of space that the type occupies;
Object-The actual amount of space occupied by the object;
Function--The amount of space that the return type of the function occupies. The return type of the function cannot be void.
Second, strlen
Strlen (...) is a function that can be evaluated at run time. The argument must be a character-type pointer (char*). When an array name is passed in as a parameter, the array is actually degenerate into a pointer.
Its function is: Returns the length of the string. The string may be self-defined or random in memory, and the function actually completes the function of iterating from the first address representing the string until the Terminator is encountered null. The returned length size does not include NULL.
C + + string when using sizeof note