Alex said:
Hi,
I have a question regarding to string variable.
Please look at below example.
------------------------------
#define STR "ABC"
char *testStr
testStr = STR;
This is perfectly correct if it appears inside a function. A statement
in C must always be within a compound block.
------------------------------
I think above example have no problem.
But I don't know where "ABC" is exist.
Does C compiler make a memory for STR?
Your question, in general, is about storage of string literals. The answer
varies under the following situations:
* The Standard recommends the string literal to be a read-only; thus,
allows sharing copies of string with identical text. In this
case, the implementation may store the sting in the code section,
or any other read-only section. This method helps perform some
optimizations.
* Many implementation provide extensions which are, generally, non
portable. One such extension is writable string literals. The
string is, then, stored in the program's static region. Thus, there
would be different copies of string literal of identical text.
Many compilers provide option to control the behaviour of character string
literals. For example, gcc provide a compiler switch, -fwritable-strings, to
store strings in writable data section. By default, GCC merges duplicate
strings, whereas, Borland's Turbo C/C++ doesn't. It provides the following
switches:
-d merge duplicate string on
-d- merge duplicate string off
Many compilers provide pragmas to control, but these are non portable.
The Standard(C99) specifies only few pragmas that are portable, and is out of
scope here.