char* str = "abcd";
char str[5] = "abcd";
比如在分配内存的时候, 还有在其他方面有什么区别
PHP中文网2017-04-17 11:26:54
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
.
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 str1
returns the byte size of the pointer str1
, and sizeof str2
returns the byte size of all elements of the array identified by str2
.
大家讲道理2017-04-17 11:26:54
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.