const char *str1 = "abcd";This statement allocates a piece of static memory in the memory to store the character array, and then assigns the first address of the character array to the pointer str1, where str1 is a pointer, use sizeof When the operator operates on it, the size of the pointer is returned.
char str2[5] = "abcd";This statement allocates a memory in the stack memory to store the character array, then assigns the first address of the character array to str2, identifies the array, and uses the sizeof operator to During its operation, what is returned is the number of elements of the array identified by the array name str2.
Update: Correction
sizeof(type)
sizeof expression
Both versions return a constant of type size_t.
1) Returns the size of the object corresponding to type type (in bytes).
2) Return the size of the object corresponding to the return type of expression (in bytes).
So there is an error in the original answer. It is now corrected as follows: sizeof str1returns the byte size of the pointer str1, and sizeof str2 returns the byte size of all elements of the array identified by str2.
The data in the former can only be read but not written, while the data in the latter can be read and written. The reason is that the data is stored in different locations and has different readable and writable attributes.
const char *str1 = "abcd";
This statement allocates a piece of static memory in the memory to store the character array, and then assigns the first address of the character array to the pointerstr1
, wherestr1
is a pointer, usesizeof
When the operator operates on it, the size of the pointer is returned.char str2[5] = "abcd";
This statement allocates a memory in the stack memory to store the character array, then assigns the first address of the character array tostr2
, identifies the array, and uses thesizeof
operator to During its operation, what is returned is the number of elements of the array identified by the array namestr2
.Update: Correction
Both versions return a constant of type
size_t
.1) Returns the size of the object corresponding to type type (in bytes).
2) Return the size of the object corresponding to the return type of expression (in bytes).
So there is an error in the original answer. It is now corrected as follows:
sizeof str1
returns the byte size of the pointerstr1
, andsizeof str2
returns the byte size of all elements of the array identified bystr2
.The data in the former can only be read but not written, while the data in the latter can be read and written. The reason is that the data is stored in different locations and has different readable and writable attributes.