A string literal is of type char[]
. When used in most contexts, a string literal (of type char[]
) decays to a pointer to its first element (it becomes type char*
).
If your compiler complains about assigning a value of type char*
(your ""
) to an object of type char*
(your var1
), your compiler is broken.
Or, most likely, you are not invoking it as a 'C' compiler, but as a compiler of a language similar to C but not quite C.
Try: gcc -Wno-write-strings ...
to disable that specific gcc extension :-)
Edit
A string literal is an array of characters (of type char[]
), but it is not modifiable. For historic (or some other peculiar) reasons they are not of type const char[]
as a "unmodifiable character array" looks like it should be.
With the "-Wwrite-strings" compiler option, gcc tries to be helpful and changes its definition of string literals.
If you want to be safe and have your string literals be of type const char[]
, just remember you're no longer compiling C (C89, C90, C99, whatever) and be happy. As other answers said: declare your pointers as const
or copy the unmodifiable characters to modifiable objects.