C string literals

I have some basic questions about string literals. I tried going through some similar SO question but I still don't get it :(.

if we have for example the following program:

char firstlit[] = "First Literal";
int main()
char secondlit[] = "Second Literal";

Are strings initialized in this way are literals? If so, how come we can modify their value? Is it undefined to change their values?

Are both of them stored in the data section? I saw somewhere that some data can be saved in the code segment, why is that?

Is the only difference between them is that secondlit contains pointer to the address which the string is initialized, but we can only use this variable in the main, while the firstlit we can use in the whole file (global)? Another question:

char *ptr = "Hello";
char secondptr[] = "Hello";

Are both of them actually the same in the way they are stored? What is the better way to use for string literals? Sorry for so much questions. Thanks.


You have exactly one string-literal object in your question:

char *ptr = "Hello"; // The array containing Hello\0

All the others are just initializers for the arrays, and there's no guarantee how, if at all, they are stored.

  • String-literals and constant compound-literals can share space and are immutable.
  • Despite that, a string-literal is of type char[] for historical reasons.
  • And there is no guarantee in what executable section they are stored, or even that there are any executable sections.
  • There is also no guarantee what happens if you disregard the fact that they are immutable. Proceed at your own peril.

Need Your Help

Spring OXM doesn't work with Struts 1

java spring struts-1 spring-oxm

I use Spring OXM as well as Struts 1 but without using integrating Struts with Spring IOC. This is because the application is an old one and I'm just adding a module that involves the XML binding a...

Call to a member function fill() on a non-object

php laravel-4

Trying to add information to an empty profile and redirect back.