Re: What is wrong with this: *p++=*s++

Jens.Toerring_at_physik.fu-berlin.de
Date: 07/26/04


Date: 26 Jul 2004 18:22:14 GMT

Hamed <hamedghm_2002@earthlink.net> wrote:
> Hi Matt,
> If you want to add mystery to your puzzle try this:
> char p [80];
> char s [80];
> p = "Hello";
> s = "world";
> Now it won't even compile. ;-) Let me know if this hint helps you figure out
> what the problem is with your code.

That's no puzzle at all.

char p[ 80 ];

gives you an array of 80 chars. And you can't change 'p' afterwards
anymore. But that's what you're trying to do when you write

p = "Hello";

because you're treating 'p' as if it where an char pointer by trying
to assign it the address of where the (6 char long) string "Hello" is
stored (possibly in read-only memory). But 'p' isn't a char pointer,
it is an array of chars. And since these are different types the
compiler won't accept that broken code.

You might be a bit confused because when you pass 'p' to a function
what the function actually gets is a pointer to the first element of
the array 'p' (instead of a copy of the array). But that is something
special about _function calls_ with array arguments and does not
change the fact that 'p' is an array which can't be converted to a
pointer here.

And the problem of the Matt has been already explained to him, strings
like the one assigned here to 's'

char *s = "Hello";

are strings that simply can't be changed but that's what he was
trying to do, violating the rules of the game (unfortunately,
there are some implementations that let you get away with this,
making learning this more difficult).
                                        Regards, Jens

-- 
  \   Jens Thoms Toerring  ___  Jens.Toerring@physik.fu-berlin.de
   \__________________________  http://www.toerring.de


Relevant Pages

  • Re: about char pointer
    ... A `char pointer` is a pointer that points to characters. ... A `char array` is an array whose elements are characters. ...
    (comp.lang.c)
  • Re: Pointer Declaration/Array definition
    ... > a char array and a char pointer are very different things, ... > with as if it would be a pointer to (the first element of) the ...
    (comp.lang.c)
  • Re: trying to read a file
    ... 'line' is a char pointer, ... it point to a "literal string", i.e. a string that can't be changed. ... not an array of chars. ...
    (comp.lang.c)
  • Re: Window Management
    ... (* prompt is a string resource identifier specifying the string ... PROCEDURE YesNoCancel(prompt: ARRAY OF CHAR; ... VAR INOUT response: ARRAY OF CHAR): BOOLEAN; ...
    (comp.lang.ada)
  • Window Management
    ... (* prompt is a string resource identifier specifying the string ... PROCEDURE YesNoCancel(prompt: ARRAY OF CHAR; ... VAR INOUT response: ARRAY OF CHAR): BOOLEAN; ...
    (comp.lang.ada)

Loading