c++ - C语言中, 如下两种定义字符串的方式有什么不同?
巴扎黑
巴扎黑 2017-04-17 11:24:54
0
2
557
char* str = "abcd";

char str[5] = "abcd";

比如在分配内存的时候, 还有在其他方面有什么区别

巴扎黑
巴扎黑

reply all(2)
Ty80
  • 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template