I am not sure if I worded the question correctly, but here it is spelled out:
char * cp = \"this is a char pointer\";
The code above, based
Your understanding is correct. A string literal is really an array of char, and taking its value really yields a pointer to its first element. You can do this for any literal array (but without the syntax sugar that you have char arrays).
char *s = "String"; // right side is array of char
int *x = (int []){1, 2}; // right side is array of int
Similarly, the following are both incorrect.
char *s = 'S';
int *x = 1;
Note the difference between "String" and 'S'. The former is an array of char, but the latter is just an int.
However (as was first mentioned by Keith), string literals and literal arrays (more generally called compound literals) have different storage duration. In particular, a string literal always has static storage duration; but a compound literal has automatic or static storage duration, depending if it appears in a function or not. This means that if you take a pointer to a compound literal from within a function:
In this respect, taking a pointer to a literal array is very similar to just declaring an array (except, for example, sizeof()):
int x[] = {1, 2};
Strings are essentially arrays of characters. Array type (e.g char[]
) variables can often be referred to as pointers (char*
, pointer to beginning of an array). That means string literals are of type char*
and that is why you can just assign that string to a pointer. On the other hand, integer literals, like '5' are of type int
, so you cannot assign it to a pointer.