How to initialize a char*?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ioannis Vranos

    #46
    Re: How to initialize a char*?

    "Julie" <julie@nospam.c om> wrote in message
    news:407C8B2D.2 799C0E8@nospam. com...[color=blue][color=green]
    > >
    > > Ok, so zero-initialisation or any other "premature" initialisation does[/color][/color]
    not[color=blue][color=green]
    > > protect you from anything. Btw try using the new C++ casts instead (of
    > > course avoid them completely if possible).
    > >
    > > Regards,
    > >
    > > Ioannis Vranos[/color]
    >
    > How do you define when "premature" is "post-mature"?[/color]


    "premature"=ini tial value not actually intended to be used.


    Too tired, going off line now. Good day/night there.






    Ioannis Vranos

    Comment

    • Buster

      #47
      Re: How to initialize a char*?

      Ioannis Vranos wrote:
      [color=blue]
      > "Buster" <noone@nowhere. com> wrote
      >[color=green]
      >>
      >>void f (char * &) { }
      >>int main ()
      >>{
      >> char c;
      >> char * p = & c;
      >> f (p);
      >>}[/color]
      >
      > But this doesn't compile:
      >
      > void f (char * &) { }
      >
      > int main ()
      > {
      > char c;
      > f (&c);
      > }[/color]

      Of course not. What would it do if it did compile?
      Modify the address of c?

      --
      Regards,
      Buster.

      Comment

      • Sam Holden

        #48
        Re: How to initialize a char*?

        On Wed, 14 Apr 2004 03:50:55 +0300,
        Ioannis Vranos <ivr@guesswh.at .emails.ru> wrote:[color=blue]
        > "Buster" <noone@nowhere. com> wrote in message
        > news:c5i0gu$dti $3@newsg2.svr.p ol.co.uk...[color=green]
        >>
        >>
        >> void f (char * &) { }
        >> int main ()
        >> {
        >> char c;
        >> char * p = & c;
        >> f (p);
        >> }[/color]
        >
        >
        >
        > But this doesn't compile:
        >
        > void f (char * &) { }
        >
        > int main ()
        > {
        > char c;
        > f (&c);
        > }[/color]

        Because the const-ness is incorrect.

        "char * &" is not the same as "char * const &".

        --
        Sam Holden

        Comment

        • Buster

          #49
          Re: How to initialize a char*?

          Sam Holden wrote:[color=blue]
          >
          >Iannis Vranos <ivr@guesswh.at .emails.ru> wrote:[color=green]
          >>
          >>But this doesn't compile:
          >>
          >>void f (char * &) { }
          >>
          >>int main ()
          >>{
          >> char c;
          >> f (&c);
          >>}[/color]
          >
          > Because the const-ness is incorrect.
          >
          > "char * &" is not the same as "char * const &".[/color]

          Kind of. The type of "& c" is not "char * const &". In fact, "& c"
          is an rvalue of type "char *". It is true that you can compile

          void f (char * const &) { }

          int main ()
          {
          char c;
          f (& c);
          }

          This is because you can bind a const reference to an rvalue.

          --
          Regards,
          Buster.

          Comment

          • Leor Zolman

            #50
            Re: How to initialize a char*?

            On Tue, 13 Apr 2004 17:08:50 -0700, Julie <julie@nospam.c om> wrote:
            [color=blue]
            >David Harmon wrote:[color=green]
            >>
            >> On Tue, 13 Apr 2004 15:47:58 -0700 in comp.lang.c++, Julie
            >> <julie@nospam.c om> wrote,[color=darkred]
            >> >Yes, my statement was directed at the 'evil' part -- there is nothing 'evil'
            >> >about it, it just has the potential to lead to undefined behavior.[/color]
            >>
            >> This issue is covered in Marshall Cline's C++ FAQ. See the topic
            >> "[6.14] What does the FAQ mean by "such-in-such is evil"?".
            >> http://www.parashift.com/c++-faq-lite/[/color]
            >
            >Thanks for pointing it out.
            >
            >After reading, that section definitely comes off as infantile and
            >inappropriat e. I'd much prefer a more precise (and less humanity-subjective)
            >term as 'evil'. But I didn't write that FAQ, nor have any plans to write one,
            >so MC is free to write what he wants. Regardless, that doesn't preclude me
            >from stating that 'evil' is a poor word choice when discussing programmatic
            >constructs and behaviors.[/color]

            Probably a bit too late to derail the use of "evil" in this context. Herb
            Sutter, Scott Meyers and others have pretty much blessed it and it is here
            to stay. I think saying "X is evil" concisely and effectively conveys the
            message "X is a legal syntactic construct that, IMHO, if not executed with
            the utmost care bordering on radical paranoia, is about as likely as
            anything else you can write in this language to lead you down the slippery
            slope into deep doo-doo, and then make it very hard for you to slog your
            way back out."
            -leor


            --
            Leor Zolman --- BD Software --- www.bdsoft.com
            On-Site Training in C/C++, Java, Perl and Unix
            C++ users: download BD Software's free STL Error Message Decryptor at:
            An STL Error Decryptor for C++ by Leor Zolman of BD Software - available to download here

            Comment

            • Christopher Benson-Manica

              #51
              Re: How to initialize a char*?

              David Harmon <source@netcom. com> spoke thus:
              [color=blue]
              > If so, it is an evil func. You can tell me which fatal error does it
              > have, buffer overflow, or thread-hostile static buffer, or dynamically
              > allocating memory that the caller will forget to free? It needs to be
              > rewritten to use std::string.[/color]

              The point of all this pedantry was merely to identify what is legal,
              not what is good practice.

              --
              Christopher Benson-Manica | I *should* know what I'm talking about - if I
              ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

              Comment

              • Old Wolf

                #52
                Re: How to initialize a char*?

                "Peter" <ybi10@yahoo.co m> wrote:[color=blue]
                >
                > So many times, I have seen compile warning: "you used a char* without
                > initilize it",[/color]

                This is the compiler being nice by telling you you have probably made
                a logic error in your program. You should fix your program, instead of
                trying to shut the compiler up.
                [color=blue]
                >probably on the code like this:
                >
                > ------------
                > char* ptr;
                >
                > func(..., ptr);[/color]

                And indeed you have made a logic error. I'm not quite sure how to
                describe the nature of this error, other than to say "you used a
                variable without initializing it". So obviously func() is not going
                to do what you wanted (unless it ignores that parameter).
                [color=blue]
                > How to properly initialize a char*?[/color]

                Well that question doesn't really make sense. It depends what func()
                is expecting. Let me replace your example by a more well-known function:

                char *ptr;
                puts(ptr);

                To "properly" initialize ptr in this example, you would have to point
                it to a string. Making it a null pointer (as some others have suggested)
                would not be an improvement.
                [color=blue]
                >I used to use
                > char* ptr = "";
                > but was told this is not good.
                > Can anybody explain to me why, and what's a good way to initilize it?[/color]

                Why does the variable even exist in the first place?
                Once you have answered that question, then you know what its value
                should be.

                Note that other people on this thread have said that you must initialize
                variables to something, before you get up to the bit where you put them
                to their intended use. This is in fact a matter of coding style;
                personally I think such initializations are a waste of time (coding time,
                run time, and maintenance time), and only serve to hide logic errors
                that might be revealed by the warning "use of uninitialized variable".
                You should do whatever seems right to you.

                Comment

                • Kevin Goodsell

                  #53
                  Re: How to initialize a char*?

                  Ioannis Vranos wrote:
                  [color=blue]
                  >
                  > Check this out:
                  >
                  >
                  > #include <iostream>
                  >
                  >
                  > int main()
                  > {
                  > using namespace std;
                  >
                  > char array[]="12345";
                  >
                  > *array='X';
                  >
                  > cout<<array<<en dl;
                  > }
                  >[/color]

                  I'm not sure what your point is here... But I'm afraid Julie is correct.
                  References to pointers are fine, and your example code demonstrated a
                  problem because you passed an incompatible type. Try it again like this:

                  void func(char * const input, int word_number, char * & ptr_to_word)
                  {
                  }


                  int main()
                  {
                  char array[]="b";
                  char *p = array;


                  func("a",5, p); // pass a pointer, not an array
                  }

                  I think you are hinting at the usual conversion ("decay") of an array
                  name to a pointer. It doesn't apply when binding to a reference.

                  -Kevin
                  --
                  My email address is valid, but changes periodically.
                  To contact me please use the address from a recent posting.

                  Comment

                  • Kevin Goodsell

                    #54
                    Re: How to initialize a char*?

                    Ioannis Vranos wrote:
                    [color=blue]
                    > "Christophe r Benson-Manica" <ataru@nospam.c yberspace.org> wrote in message
                    > news:c5hbdn$e0l $1@chessie.cirr .com...
                    >[color=green]
                    >>Peter <ybi10@yahoo.co m> spoke thus:
                    >>
                    >>[color=darkred]
                    >>>char* ptr;
                    >>>func(..., ptr);[/color]
                    >>
                    >>This is bad - ptr is uninitialized (not even NULL), so passing it to a
                    >>function is either pointless or an invitation to disaster, a mistake
                    >>in any case.[/color]
                    >
                    > Why?
                    >[/color]

                    Assuming ptr is being passed by value, the behavior is undefined. You
                    are generally only allowed to do a few things with an uninitialized
                    variable. For example, you can assign to it, take its address, bind it
                    to a reference, apply 'sizeof' to it, etc. However, inspecting the value
                    (as must be done to make a copy when passing to a function) is not
                    permitted.

                    The technical details of this are described in the standard in the
                    section about converting from a lvalue to an rvalue, if I recall
                    correctly. Essentially, this conversion is not defined for an
                    uninitialized lvalue.
                    [color=blue]
                    >
                    >[color=green][color=darkred]
                    >>>How to properly initialize a char*? I used to use[/color]
                    >>[color=darkred]
                    >>>char* ptr = "";[/color]
                    >>
                    >>Depends on what you're doing with it. You probably were told that
                    >>because it should be
                    >>
                    >>const char *ptr="";[/color]
                    >
                    > And what would be the use of that?
                    >[/color]

                    You should not assign a string literal to a non-const char pointer. This
                    is a deprecated and dangerous conversion, included for C compatibility.
                    In both languages it is dangerous. In C++, the type of a string literal
                    is 'const char[N]' where N is chosen to be the appropriate size. The
                    conversion to (non-const) char* is permitted, but breaks
                    const-correctness and allows code that attempts to modify a
                    const-object, causing undefined behavior.
                    [color=blue]
                    >
                    >
                    >[color=green]
                    >>Why? Because "" is a constant empty string; trying to modify it
                    >>invites disaster. Therefore, pointers to such string literals (so
                    >>they're called) should be declared const; that way if you try to
                    >>modify what it points to the compiler can inform you of your mistake.[/color]
                    >
                    > The above is entirely, completely useless.
                    >[/color]

                    I don't understand why you think it is useless. If your point is that
                    the assignment itself is wrong, you may be right. We don't know what
                    he's doing, but it seems likely that pointing to a string literal is not
                    useful (particularly when it is done only to silence a warning).

                    -Kevin
                    --
                    My email address is valid, but changes periodically.
                    To contact me please use the address from a recent posting.

                    Comment

                    • Kevin Goodsell

                      #55
                      Re: How to initialize a char*?

                      Ioannis Vranos wrote:
                      [color=blue]
                      > "Kevin Goodsell" <usenet2.spamfr ee.fusion@never box.com> wrote in message
                      > news:s_Xec.8580 $A_4.7680@newsr ead1.news.pas.e arthlink.net...
                      >[color=green]
                      >>This uses a dangerous and deprecated language feature -- the implicit
                      >>conversion of a string literal to a (non-const) char*. I'd suggest
                      >>making your compiler warn about this if it provides such a warning.[/color]
                      >
                      >
                      > Eh?[/color]

                      I'd be happy to clarify if you'll tell me which part you have a problem
                      with. I did already go over this in a bit more detail elsewhere in the
                      thread (in another reply to you, I believe), so you might check there first.

                      If you want to check the standard you can find this in D.4
                      [depr.string]. There's also information in 4.2/2 [conv.array]. Finally,
                      2.13.4 explicitly states that string literals consist of const
                      characters, and I know it's stated somewhere that modifying const
                      objects gives undefined behavior, but I'm not sure where to look.
                      [color=blue]
                      >[color=green]
                      >>Initialize it with whatever you need. You're the only one who knows what
                      >>purpose it serves, so we can't suggest what to use. But leaving it
                      >>uninitializ ed is an error, and doesn't make sense.[/color]
                      >
                      >
                      > It is not an error![/color]

                      Failing to initialize in itself is not an error. But using the
                      uninitialized value is undefined behavior.

                      -Kevin
                      --
                      My email address is valid, but changes periodically.
                      To contact me please use the address from a recent posting.

                      Comment

                      • Kevin Goodsell

                        #56
                        Re: How to initialize a char*?

                        Kevin Goodsell wrote:
                        [color=blue]
                        > I don't understand why you think it is useless. If your point is that
                        > the assignment itself is wrong, you may be right.[/color]

                        Should be "the initialization itself". And judging from your other
                        replies, I guess this is what you meant. The initialization to an
                        arbitrary string literal is probably not useful.

                        -Kevin
                        --
                        My email address is valid, but changes periodically.
                        To contact me please use the address from a recent posting.

                        Comment

                        • Gary Labowitz

                          #57
                          Re: How to initialize a char*?

                          "Buster" <noone@nowhere. com> wrote in message
                          news:c5i5vm$jnh $1@newsg1.svr.p ol.co.uk...[color=blue]
                          > Sam Holden wrote:[color=green]
                          > >
                          > >Iannis Vranos <ivr@guesswh.at .emails.ru> wrote:[color=darkred]
                          > >>
                          > >>But this doesn't compile:
                          > >>
                          > >>void f (char * &) { }
                          > >>
                          > >>int main ()
                          > >>{
                          > >> char c;
                          > >> f (&c);
                          > >>}[/color][/color][/color]
                          <<snip>>
                          And after all the smoke clears we find ...

                          #include <iostream>
                          using namespace std;

                          int main( )
                          {
                          void change(const char*, char* &);

                          char s[10]= {"x"};
                          char* ptr = &s[0];
                          cout << "content of pointer is " << ptr << endl;
                          change("ABC", ptr);
                          cout << "content of pointer is " << ptr << endl;
                          return 0;
                          }

                          void change(const char* nus, char* &nup)
                          {
                          strcpy(nup, nus);
                          return;
                          }

                          --
                          Gary


                          Comment

                          • Buster

                            #58
                            Re: How to initialize a char*?

                            Gary Labowitz wrote:
                            [color=blue]
                            > And after all the smoke clears we find ...[/color]
                            [snip]

                            Maybe you shouldn't smoke that stuff during the week.

                            #include <ostream>
                            #include <iostream>

                            void redirect (char const * & reference, char const * pointer)
                            { reference = pointer; }

                            int main ()
                            {
                            char const * p = "Hello.\n";
                            redirect (p, "Goodbye.\n ");
                            std::cout << p;
                            }

                            --
                            Regards,
                            Buster.

                            Comment

                            • Christopher Benson-Manica

                              #59
                              Re: How to initialize a char*?

                              Kevin Goodsell <usenet2.spamfr ee.fusion@never box.com> spoke thus:
                              [color=blue]
                              > Should be "the initialization itself". And judging from your other
                              > replies, I guess this is what you meant. The initialization to an
                              > arbitrary string literal is probably not useful.[/color]

                              There are better alternatives, I'm sure, but IMHO the following is
                              "useful":

                              const char * const err_string = "Error: " __FILE__ " " __LINE__;

                              --
                              Christopher Benson-Manica | I *should* know what I'm talking about - if I
                              ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

                              Comment

                              • Ioannis Vranos

                                #60
                                Re: How to initialize a char*?

                                "Kevin Goodsell" <usenet2.spamfr ee.fusion@never box.com> wrote in message
                                news:RI4fc.9510 $A_4.5799@newsr ead1.news.pas.e arthlink.net...[color=blue]
                                > Ioannis Vranos wrote:
                                >[color=green]
                                > >
                                > > Check this out:
                                > >
                                > >
                                > > #include <iostream>
                                > >
                                > >
                                > > int main()
                                > > {
                                > > using namespace std;
                                > >
                                > > char array[]="12345";
                                > >
                                > > *array='X';
                                > >
                                > > cout<<array<<en dl;
                                > > }
                                > >[/color]
                                >
                                > I'm not sure what your point is here... But I'm afraid Julie is correct.
                                > References to pointers are fine, and your example code demonstrated a
                                > problem because you passed an incompatible type. Try it again like this:
                                >
                                > void func(char * const input, int word_number, char * & ptr_to_word)
                                > {
                                > }
                                >
                                >
                                > int main()
                                > {
                                > char array[]="b";
                                > char *p = array;
                                >
                                >
                                > func("a",5, p); // pass a pointer, not an array
                                > }
                                >
                                > I think you are hinting at the usual conversion ("decay") of an array
                                > name to a pointer. It doesn't apply when binding to a reference.[/color]


                                My point for the above code was that the name of an array is "converted" as
                                a pointer to the first element which in this case is char *. She had said:

                                "The function takes a reference argument of type char *, you are
                                (attempting) to pass a type of char[2]."


                                I was passing a "char *" as an address, the real problem was that the
                                function was accepting a char * & and there was not a char * object, so it
                                naturally failed.


                                Anyway i had expressed myself erroneusly in the beginning regarding the char
                                * &, and we got astray of the original subject which was about "premature
                                initialisation" , that is initialisation with a value which is not going to
                                be used, but only to protect us. Such an initialisation does not protect us
                                in any way.






                                Ioannis Vranos

                                Comment

                                Working...