I encountered a small computation during the C ++ review. I still have a lot of knowledge. Let's start with your attention!
Char * str1 = "absde"; char str2 [] = "absde"; char str3 [8] = {'A' ,}; char ss [] = "0123456789 "; why sizeof (str1) = 4 sizeof (str2) = 6; sizeof (str3) = 8; sizeof (SS) = 11
First of all, the char type occupies one byte, so sizeof (char) is 1. To understand this, str1 is a pointer, but it only points to the string "absde. Therefore, sizeof (str1) is not the space occupied by strings, nor the space occupied by character arrays, but the space occupied by a character pointer. Therefore, sizeof (str1) = sizeof (char *) = 4. in C/C ++, a pointer occupies 4 bytes. str2 is a struct array. C/C ++ specifies that for an array, the total space occupied by this array is returned. Therefore, sizeof (str2) obtains the total space occupied by the string "absde. In "absde", there are
B s d e \ 0 six characters, so the str2 array length is 6, so sizeof (str2) = 6 * sizeof (char) = 6str3 has been defined as an array with a length of 8, so sizeof (str3) is similar to 8str4 and str2, '0' '1 '... '9' and '\ 0' are 11 characters in total, so SS occupies 8 space. For pointers, the sizeof operator returns the space occupied by the pointer, which is generally 4 bytes; for an array, sizeof returns the total space occupied by all elements in the array. Char * and char [] are easy to confuse and must be distinguished. In addition, char * = "AAA" is not recommended and should be avoided, while strlen does not distinguish array or pointer, returns the length until \ 0. In addition, strlen does not include \ 0 in the length of the string.
In general:
Sizeof is the length of the Data Type it refers,
Char * str1 = "absde ";
Str1 is a pointer, and the length of a char pointer is 4.
Char str2 [] = "absde ";
Char str3 [8] = {'A ',};
Char ss [] = "0123456789 ";
Str2, str3, and SS are all arrays. The result of sizeof is the length of the Data Type (array ).