Difference between char* and char array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ambar.shome@gmail.com

    Difference between char* and char array

    Can anyone tell me :

    1.
    void main()
    {

    char temp[] = "Hello";

    temp[0]='K';

    }
    2.

    void main()
    {

    char* temp = "Hello";

    temp[0]='K';

    }

    1st one gives an access violation whereas second one is done
    successfully. I want to know why the fist one gives a runtime-error? I
    want to know what happens internally? How the compiler interprets this
    two snippets?

  • Rolf Magnus

    #2
    Re: Difference between char* and char array

    ambar.shome@gma il.com wrote:
    [color=blue]
    > Can anyone tell me :
    >
    > 1.
    > void main()
    > {
    >
    > char temp[] = "Hello";
    >
    > temp[0]='K';
    >
    > }
    > 2.
    >
    > void main()
    > {
    >
    > char* temp = "Hello";
    >
    > temp[0]='K';
    >
    > }
    >
    > 1st one gives an access violation whereas second one is done
    > successfully.[/color]

    Actually, both are incorrect. main must always return int.
    [color=blue]
    > I want to know why the fist one gives a runtime-error?[/color]

    The first shouldn't produce an error, but the second may.
    [color=blue]
    > I want to know what happens internally? How the compiler interprets this
    > two snippets?[/color]

    In the first one, an array of 6 char is created locally in the function and
    the contents of the string literal "Hello" is copied into it. Afterwards,
    you overwrite the first element of that array.
    In the second snippet, a pointer to the first character literal itself is
    created. This pointer should better be a const char*, because string
    literals are constant and must not be modified. When you try to write to
    temp[0], you access read-only memory.

    Comment

    • ambar.shome@gmail.com

      #3
      Re: Difference between char* and char array

      Actually, both are incorrect. main must always return int.[color=blue][color=green]
      >> I know when you return something (integer) from main it goes back to the progammers environment. I also know you are right main always should return int. But, why is it like that? whats the use of it?[/color][/color]

      Comment

      • Jakob Bieling

        #4
        Re: Difference between char* and char array

        <ambar.shome@gm ail.com> wrote in message
        news:1121633924 .834625.181200@ o13g2000cwo.goo glegroups.com.. .[color=blue][color=green]
        >> Actually, both are incorrect. main must always return int.[/color][/color]
        [color=blue]
        > I know when you return something (integer) from main it
        > goes back to the progammers environment. I also know you
        > are right main always should return int. But, why is it
        > like that? whats the use of it?[/color]

        Because the 'integer from main goes back to the programs
        environment.' The environment may do whatever it likes, including
        nothing. So for the programmers point of view, it's not really of
        interest, what will be done with the return value. It's only important
        that we must play by the rules .. ie. the Standard.

        If you do not, imagine an environment where return values are passed
        on the stack. So the caller of your program needs to remove the return
        value, no matter if it needs it or not. If you return void, you never
        put something on the stack .. but the environment does not know that,
        right? So instead of wiping your (should-be-but-is-not-existant) return
        value, it will remove other information .. and you can expect this to
        end in a not user-friendly way.

        regards
        --
        jb

        (reply address in rot13, unscramble first)


        Comment

        • ambar.shome@gmail.com

          #5
          Re: Difference between char* and char array

          >If you do not, imagine an environment where return values are >passed[color=blue]
          >on the stack. So the caller of your program needs to remove the >return value[/color]

          Why the caller of my program will be attempting to remove the return
          value if i declare my main()
          functions as " void main() { }". As you can see I have already
          mentioned that main() is not going to return any value, so tha caller
          should not make any attempt to remove return value.

          Thanks in advance..

          Regards
          Ambar

          Comment

          • Jakob Bieling

            #6
            Re: Difference between char* and char array

            <ambar.shome@gm ail.com> wrote in message
            news:1121636015 .150036.49470@z 14g2000cwz.goog legroups.com...[color=blue][color=green]
            > >If you do not, imagine an environment where return values are >passed
            >>on the stack. So the caller of your program needs to remove the[color=darkred]
            >> >return value[/color][/color]
            >
            > Why the caller of my program will be attempting to remove the return
            > value if i declare my main()
            > functions as " void main() { }". As you can see I have already
            > mentioned that main() is not going to return any value, so tha caller
            > should not make any attempt to remove return value.[/color]


            You told the compiler. Not the environment. That is a difference.

            regards
            --
            jb

            (reply address in rot13, unscramble first)


            Comment

            • Rolf Magnus

              #7
              Re: Difference between char* and char array

              ambar.shome@gma il.com wrote:
              [color=blue][color=green]
              >>If you do not, imagine an environment where return values are >passed
              >>on the stack. So the caller of your program needs to remove the >return
              >>value[/color]
              >
              > Why the caller of my program will be attempting to remove the return
              > value if i declare my main() functions as " void main() { }".[/color]

              Because the C++ standard says that a program always must return int. The
              caller of your program might count on that and just expect your program to
              do it.
              [color=blue]
              > As you can see I have already mentioned that main() is not going to return
              > any value, so tha caller should not make any attempt to remove return
              > value.[/color]

              The caller doesn't necessarily know that you didn't play by the rules.

              Comment

              • Greg

                #8
                Re: Difference between char* and char array

                Rolf Magnus wrote:[color=blue]
                > ambar.shome@gma il.com wrote:
                >[color=green][color=darkred]
                > >>If you do not, imagine an environment where return values are >passed
                > >>on the stack. So the caller of your program needs to remove the >return
                > >>value[/color]
                > >
                > > Why the caller of my program will be attempting to remove the return
                > > value if i declare my main() functions as " void main() { }".[/color]
                >
                > Because the C++ standard says that a program always must return int. The
                > caller of your program might count on that and just expect your program to
                > do it.
                >[color=green]
                > > As you can see I have already mentioned that main() is not going to return
                > > any value, so tha caller should not make any attempt to remove return
                > > value.[/color]
                >
                > The caller doesn't necessarily know that you didn't play by the rules.[/color]

                Actually, the C++ standard states that main must be declared to return
                an int, it does not require that the program's main routine actually do
                so, that is, to return an int or to return anything at all. It is
                perfectly legal for a C++ program to "fall off" the end of the main
                routine without ever executing a return statement.

                In the case that a C++ program reaches the end of main, the program
                terminates and the value 0 is returned to the environment. And as a
                practical matter, it's likely that most implementations would always
                have the program return 0 to the environment in this situation, no
                matter the declaration of main.

                Even if the 0 were not supplied, the return value of a program or a
                function call on most systems is placed in a register. So there is
                little danger of the caller "removing" a value that is not present, and
                fouling things up. Rather whatever value is found in the register on
                program exit is taken to be the result returned by the program. Whether
                the program itself determined that value, or the C++ compiler did so on
                the program's behalf, is not known by, nor should it make any
                difference to, the caller.

                Greg

                Comment

                • Me

                  #9
                  Re: Difference between char* and char array

                  ambar.shome@gma il.com wrote:[color=blue]
                  > Can anyone tell me :
                  >
                  > 1.
                  > char temp[] = "Hello";
                  > temp[0]='K';[/color]

                  In this example,

                  char temp[] = "Hello";

                  is just syntax sugar for:

                  char temp[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
                  [color=blue]
                  > 2.
                  >
                  > char* temp = "Hello";
                  > temp[0]='K';[/color]

                  In this example, "Hello" is a const char[6] (i.e. a 6 element array of
                  const chars). Unfortunately, due to backwards compatibility with legacy
                  C code, the current C++ standard allows arrays of const char to decay
                  to char * during standard conversions as a special case (otherwise you
                  would be required to do const char *temp = "Hello"). Just because you
                  can implicitly convert to it as a special case doesn't mean assigning
                  to it becomes legal all of a sudden. It's the same reason the following
                  is illegal:

                  const char c = 'H';
                  char *temp = const_cast<char *>(&c);
                  *temp = 'K';
                  [color=blue]
                  > 1st one gives an access violation whereas second one is done
                  > successfully. I want to know why the fist one gives a runtime-error? I
                  > want to know what happens internally? How the compiler interprets this
                  > two snippets?[/color]

                  I think you got this backwards. The first example is legal whereas the
                  second one is undefined.

                  Comment

                  • Jakob Bieling

                    #10
                    Re: Difference between char* and char array

                    "Greg" <greghe@pacbell .net> wrote in message
                    news:1121644747 .113796.109000@ g47g2000cwa.goo glegroups.com.. .
                    [color=blue]
                    > Even if the 0 were not supplied, the return value of a program or a
                    > function call on most systems is placed in a register. So there is
                    > little danger of the caller "removing" a value that is not present,
                    > and[/color]

                    'most' depends on what you work with. To be honest, I have no ideas
                    if such machines exist, but why should this make me not play by the
                    rules. You seem to be discouraging people from using 'int main', because
                    'void main' is not such a big deal to you. Why not look at it the other
                    way round: a) you play by the rules, b) you do not have to watch out for
                    it when coding for a new system, and c) you even have to type less.

                    The bottom line is: even though 'void main' might work for you and
                    your friends, 'int main' will save you trouble in the end; there's no
                    reason not to go for 'int main'.

                    regards
                    --
                    jb

                    (reply address in rot13, unscramble first)


                    Comment

                    • ambar.shome@gmail.com

                      #11
                      Re: Difference between char* and char array

                      Hi,
                      I am not discouraging

                      Comment

                      • ambar.shome@gmail.com

                        #12
                        Re: Difference between char* and char array

                        Hi,

                        I am not discouraging people from using 'int main'. If using 'int main'
                        is a standard then there must be some reason to follow that standard. I
                        am just trying to find out that reason. So far what you said and what
                        Greg said are not in sync at all. Greg stated
                        "In the case that a C++ program reaches the end of main, the program
                        terminates and the value 0 is returned to the environment"
                        and "Even if the 0 were not supplied, the return value of a program or
                        a function call on most systems is placed in a register. "

                        Now you said ". If you return void, you never put something on the
                        stack .. but the environment does not know that, " .
                        I am totally confused and cant decide which one I should accept. May be
                        only Stroustrup can tell us what exactly happens . Or can you guys can
                        synchoronize your statements so that I can accept that as final. I
                        really need to know this.

                        Thanking you in advance.

                        Ambar

                        Comment

                        • Karl Heinz Buchegger

                          #13
                          Re: Difference between char* and char array

                          ambar.shome@gma il.com wrote:[color=blue]
                          >
                          > Now you said ". If you return void, you never put something on the
                          > stack .. but the environment does not know that, " .
                          > I am totally confused and cant decide which one I should accept. May be
                          > only Stroustrup can tell us what exactly happens .[/color]

                          No one can tell you what exactly will happen, because here you are at an
                          interface. The interface connects your program with the outside
                          world.
                          Well the outside world is fixed and it might or it might not expect
                          the program to return an int in some way. But neither you, nor your program
                          can't change that. If that outside world expects your program to return
                          an int in some way, and your program doesn't play by the rules, then
                          anything imaginable might happen.
                          Before you ask: Yes, the outside world has every right to expect your
                          program to return an int. The rules of C++ dictate that the program *must*
                          return an int, so the outside world can rely on that fact.

                          Even if your development environment lets you get away with void main(), it doesn't
                          mean it is correct to do so.

                          --
                          Karl Heinz Buchegger
                          kbuchegg@gascad .at

                          Comment

                          • Rolf Magnus

                            #14
                            Re: Difference between char* and char array

                            Greg wrote:
                            [color=blue]
                            > Rolf Magnus wrote:[color=green]
                            >> ambar.shome@gma il.com wrote:
                            >>[color=darkred]
                            >> >>If you do not, imagine an environment where return values are >passed
                            >> >>on the stack. So the caller of your program needs to remove the >return
                            >> >>value
                            >> >
                            >> > Why the caller of my program will be attempting to remove the return
                            >> > value if i declare my main() functions as " void main() { }".[/color]
                            >>
                            >> Because the C++ standard says that a program always must return int. The
                            >> caller of your program might count on that and just expect your program
                            >> to do it.
                            >>[color=darkred]
                            >> > As you can see I have already mentioned that main() is not going to
                            >> > return any value, so tha caller should not make any attempt to remove
                            >> > return value.[/color]
                            >>
                            >> The caller doesn't necessarily know that you didn't play by the rules.[/color]
                            >
                            > Actually, the C++ standard states that main must be declared to return
                            > an int, it does not require that the program's main routine actually do
                            > so, that is, to return an int or to return anything at all. It is
                            > perfectly legal for a C++ program to "fall off" the end of the main
                            > routine without ever executing a return statement. In the case that a C++
                            > program reaches the end of main, the program terminates and the value 0 is
                            > returned to the environment[/color]

                            I'd rather describe it like this: If you declare main() to return int, it
                            does return int. The C++ standard just contains an exception for main()
                            that you don't need to write down the return statement. If you don't, 0
                            will implicitly be returned. This is guaranteed.
                            [color=blue]
                            > . And as a
                            > practical matter, it's likely that most implementations would always
                            > have the program return 0 to the environment in this situation, no
                            > matter the declaration of main.[/color]

                            Words like "likely" and "most" already indicate that it's not necessarily
                            the case for all implementations . So what's the advantage of doing
                            something that is likely to work instead of something that is formally
                            correct and guaranteed to work?
                            [color=blue]
                            > Even if the 0 were not supplied, the return value of a program or a
                            > function call on most systems is placed in a register. So there is
                            > little danger of the caller "removing" a value that is not present, and
                            > fouling things up.[/color]

                            Well, it depends on the environment. If it does do what you describe, there
                            is no danger at all. If it doesn't, there is great danger. You cannot
                            average the danger.

                            Comment

                            • Rolf Magnus

                              #15
                              Re: Difference between char* and char array

                              Me wrote:
                              [color=blue]
                              > Unfortunately, due to backwards compatibility with legacy C code, the
                              > current C++ standard allows arrays of const char to decay to char * during
                              > standard conversions as a special case (otherwise you would be required to
                              > do const char *temp = "Hello").[/color]

                              This is only true for string literals.

                              char * c = "Hello"; // ok, even though the literal is of type const char[6].
                              const char[] d = "Hello";
                              char* e = d; // error, because of ignoring const.

                              [color=blue]
                              > Just because you can implicitly convert to it as a special case doesn't
                              > mean assigning to it becomes legal all of a sudden.[/color]

                              The conversion is legal. Using the pointer to write to the string literal is
                              not.

                              Comment

                              Working...