Ian Collins <ian-> writes:
> Brice Rebsamen wrote:
>> Reading the code from showkey.c (from package kbd) I found this type
>> of code:
>>
>> char *m;
>> m = "RAW";
>>
> The character pointer m (which should probably be a const char*) points
> to the string literal "RAW".
>
>> See below for the complete code. How can this work? I would have used
>> strdup, or allocation of the memory for m (static or dynamic) then
>> strncpy.
>>
> Remember m it a pointer.
I suspect Brice's confusion is based not on the fact that m is a
pointer (it obviously is, since it's declared that way), but on the
fact that "RAW" isn't a pointer.
If you're unfamiliar with C, you know that "=" is an assignment
operator, and that it causes the value of the right hand side to be
copied to the object named by the left hand side. In this case, you
might assume that the characters 'R', 'A', and 'W' (and the trailing
'\0') are going to be copied -- but it ain't so.
A string literal is an array of char. The trick is that, like any
expression of array type, it's implicitly converted to a pointer to
the array's first element in most contexts. This conversion doesn't
happen when the array is the operand of a unary "&" or "sizeof"
operator, or when it's a string literal use to initialize an array.
(In case you were wondering, the last case doesn't apply here, since
(a) it's an assignment, not an initializer, and (b) the object being
initialized^H^H^H^H^H^H^H^H^H^H^H assigned to isn't an array.)
So the assignment
m = "RAW";
copies, not the string "RAW", but the address of its first character,
into m.
The relationship between arrays and pointers in C can be confusing,
and some features of the language almost seem to have been designed to
maintain that confusion. The best cure I know of is to read and
understand section 6 of the comp.lang.c FAQ, <http://www.c-faq.com/>.
--
Keith Thompson (The_Other_Keith) <kst->
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
|