DWQA QuestionsCategory: ProgramIn C, what are the differences between the following two ways of defining strings?
X140Yu asked 1 month ago
char* str = "abcd";

char str[5] = "abcd";

For example, when allocating memory, what are the other differences

2 Answers
Best Answer
Sakura air release answered 1 month ago
  • const char *str1 = "abcd";This statement allocates a block in memoryStatic memoryStore the character array, and then assign the first address of the character array to the pointerstr1Here.str1It’s a pointer. UsesizeofWhen an operator operates on it, it returns the size of the pointer.
  • char str2[5] = "abcd";This statement is inStack memoryThe first address of the character array is given tostr2, identify the array withsizeofWhen the operator operates on it, it returns the array namestr2The number of elements of the identified array.
    Update: correction
sizeof(type)        
sizeof expression   

Both versions return onesize_tConstant of type.
1) return the size of the object corresponding to the type (in order tobyteIn units).
2) return the size of the object corresponding to the return type of the expression (withbyteIn units).
So the original answer is wrong. Now it is corrected as follows:sizeof str1Pointer returnedstr1Byte size of,sizeof str2The return isstr2The byte size of all elements of the identified array.

brayden replied 1 month ago

“When the sizeof operator is used to operate on it, it returns the number of elements of the array identified by the array name STR2. “

iSayme answered 1 month ago

The former can only read and write data, while the latter can read and write data