What is the difference between these two initializations?
char a[] = "string literal";
char *p = "string literal";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Each forces the compiler to create a string literal in static memory that’s (at least conceptually) read-only.
The first then uses that to initialize the contents of an array. The string literal is just used to pick its size, and to initialize it.
The second creates a pointer directly to the original string literal itself.
There is no real better or worse between them. They’re just different. For example, the array usually uses more memory (there’s a string literal, then there’s a complete copy of the string literal in your array). Since it’s an otherwise normal array, however, you can modify it if necessary.
The pointer directly to the string literal will often save some memory. It also means you can assign a different value to the pointer so that it (for example) points at different string literals at different times. You are not, however, allowed to modify the data it points at — doing so will give undefined behavior.