const char* = new char[6]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Frederick Gotham

    #31
    Re: const char* = new char[6]

    S S posted:
    >This behaviour of this statement is well-defined, as it does not modify
    >const data.
    >>
    >
    Yes, but it would have been undefined if I would have written
    char const *p = new char const[6];

    You are correct.

    Can you please give 2 syntaxes in the given context where
    we strip away constness

    First of all, let's start off with guinea pig: a const pointer to a const
    int:

    int const *const p;
    const int *const p; /* These two are the same */

    1- for pointer itself is const

    This would only make sense if you want to yield an L-value, so I will cast
    to a reference type. (Unless you cast to a reference type, a cast always
    yields an R-value in C++.)

    const_cast<int const*&>(p)

    2- data is const

    To yield an R-value: const_cast<int* >(p)

    or,

    To yield an L-value: const_cast<int* const&>(p)

    (Not that I didn't write const_cast<int* constfor the first one -- reason
    being that it would have been redundant because the cast yields an R-
    value.)

    3- both
    Yield an L-value:

    const_cast<int* &>(p)

    --

    Frederick Gotham

    Comment

    • Frederick Gotham

      #32
      Re: const char* = new char[6]

      S S posted:
      Incorrect, type of "hello" is const char[]
      that can be confirmed when you overload the function
      void func(char* str); //1st fxn
      void func(const char* str); //2nd fxn
      func("hello"); // calls the 2nd fxn
      That is indeed quite a funky example... I've got a question for comp.std.c++.

      --

      Frederick Gotham

      Comment

      • S S

        #33
        Re: const char* = new char[6]


        Frederick Gotham wrote:
        S S posted:
        >
        This behaviour of this statement is well-defined, as it does not modify
        const data.
        >
        Yes, but it would have been undefined if I would have written
        char const *p = new char const[6];
        >
        >
        You are correct.
        >
        >
        Can you please give 2 syntaxes in the given context where
        we strip away constness
        >
        >
        First of all, let's start off with guinea pig: a const pointer to a const
        int:
        >
        int const *const p;
        const int *const p; /* These two are the same */
        >
        >
        1- for pointer itself is const
        >
        >
        This would only make sense if you want to yield an L-value, so I will cast
        to a reference type. (Unless you cast to a reference type, a cast always
        yields an R-value in C++.)
        >
        const_cast<int const*&>(p)
        >
        >
        2- data is const
        >
        >
        To yield an R-value: const_cast<int* >(p)
        >
        or,
        >
        To yield an L-value: const_cast<int* const&>(p)
        >
        (Not that I didn't write const_cast<int* constfor the first one -- reason
        being that it would have been redundant because the cast yields an R-
        value.)
        >
        >
        3- both
        >
        Yield an L-value:
        >
        const_cast<int* &>(p)
        >
        Bingo!!!
        Thanks for explanation, that is what I was most confused about.

        --
        >
        Frederick Gotham

        Comment

        • Thomas J. Gritzan

          #34
          Re: const char* = new char[6]

          benben schrieb:
          Either do
          >
          char p[] = {'h', 'e', 'l', 'l', 'o', 0};
          p[0] = 'K'; // OK
          Same as this (which is shorter & easier to read):
          char p[] = "hello";
          p[0] = 'K';
          or
          >
          char* p = new char[6];
          >
          if (p != 0)
          {
          No need to check the pointer. It can't be null here.
          strcpy(p, "hello");
          p[0] = 'K'; // OK
          delete[] p;
          }
          Or even better, use std::string
          >
          std::string str = "Hello";
          str[0] = 'K'; // also ok
          >
          Notice that any of the examples (especially the last one) are elegant,
          and above all, correct, compared to your solutions with const_cast.
          If the OP wants a constant string:

          const std::string str = "Hello";

          He should start using the C++ features (strings and IO-streams) and come
          back to plain array and pointers only when he really needs the better
          performance.

          --
          Thomas

          Comment

          • S S

            #35
            Re: const char* = new char[6]


            Frederick Gotham wrote:
            Rolf Magnus posted:
            >
            You would be correct to think that the altering of a string literal
            produces undefined behaviour, but nonetheless, string literals are not
            const.
            I'll answer that with a quote from the standard:

            2.13.4 String literals

            [...]
            An ordinary string literal has type "array of n const char" and
            static storage duration (3.7), where n is the size of the string as
            defined below, and is initialized with the given characters.
            >
            >
            I stand corrected.
            >
            void Func(char (&str)[6]) {}
            Put const and compile error will go away
            void Func(const char (&str)[6]) {}
            I did not get what you actually wanted to say here.
            >
            int main()
            {
            Func("Hello"); /* Compile ERROR */
            }
            >
            --
            >
            Frederick Gotham

            Comment

            • S S

              #36
              Re: const char* = new char[6]


              Frederick Gotham wrote:
              S S posted:
              >
              I am sorry, please read my first line as
              char * p = "hello";
              in my previous mail
              >
              >
              Extremely il-advised. You're storing the address of non-modifiable data in a
              pointer to non-const.
              >
              >
              But I am able to get the desired result by the following way , but I am
              amazed how it has worked?

              const char* ptrc = new char[6];
              >
              >
              Here you store the address of non-const data in a pointer to const. Be
              consistent! Either use:
              >
              char const *const p = new char const[6];
              This is not compiling, saying uninitialized const in `new' of `const
              char'
              How to initialize it
              If I give
              char const *const p = new char const[6]("hello");
              It compiles fine but if I try to print p, it does not show value hello,
              jus blank line
              Any idea Frederick?
              >
              or:
              >
              char *const p = new char[6];
              >
              >
              memcpy(const_ca st<char*>(ptrc) ,"hello",6);
              >
              >
              This behaviour of this statement is well-defined, as it does not modify const
              data.
              >
              >
              //memcpy((char*)p trc,"hello",6); // this also works
              >
              >
              Yes, this is equivalent.
              >
              >
              printf("%s\n",p trc); // hello
              >
              >
              You're mixing C and C++ all over the place! If you're hell-bent on using C
              functions in C++ code, you must change:
              >
              #include <stdio.h>
              >
              printf(...
              >
              to:
              >
              #include <cstdio>
              >
              std::printf(...
              >
              >
              const_cast<char &>(ptrc[0]) = 'K'; //Kello
              >
              >
              Again, the behaviour is well-defined because the data is ours to modify.
              >
              >
              My question is "How I am able to modify the constness of memory by
              using 2nd statement which actually is supposed to remove the constness
              of pointers only???
              >
              >
              Your question is flawed. The following denotes a const pointer:
              >
              char *const p;
              >
              The following two denote a pointer to const:
              >
              char const *p;
              const char *p;
              >
              The following two denote a const pointer to const:
              >
              char const *const p;
              const char *const p;
              >
              A "const_cast " can be used to strip away either of the constnesses (i.e.
              whether the pointer itself is const, or whether the data it points to may be
              modified by the pointer in question.)
              >
              Is my compiler wrong?
              >
              You'll get your head around all this soon enough. Keep asking questions until
              you're absolutely certain you know what's going on -- that's what sets the
              good programmers from the great programmers.
              >
              --
              >
              Frederick Gotham

              Comment

              • Rolf Magnus

                #37
                Re: const char* = new char[6]

                S S wrote:
                >
                Frederick Gotham wrote:
                >Rolf Magnus posted:
                >>
                >You would be correct to think that the altering of a string literal
                >produces undefined behaviour, but nonetheless, string literals are not
                >const.
                >
                I'll answer that with a quote from the standard:
                >
                2.13.4 String literals
                >
                [...]
                An ordinary string literal has type "array of n const char" and
                static storage duration (3.7), where n is the size of the string as
                defined below, and is initialized with the given characters.
                >>
                >>
                >I stand corrected.
                >>
                > void Func(char (&str)[6]) {}
                >
                Put const and compile error will go away
                Yes. That was the point.
                void Func(const char (&str)[6]) {}
                I did not get what you actually wanted to say here.
                He wanted to say that string literals are const. The fact that the above
                fails without const proves it.
                > int main()
                > {
                > Func("Hello"); /* Compile ERROR */
                > }
                >>
                >--
                >>
                >Frederick Gotham

                Comment

                • Frederick Gotham

                  #38
                  Re: const char* = new char[6]

                  S S posted:
                  > char const *const p = new char const[6];
                  >
                  This is not compiling, saying uninitialized const in `new' of `const
                  char' How to initialize it If I give char const *const p = new char
                  const[6]("hello"); It compiles fine but if I try to print p, it does not
                  show value hello, jus blank line Any idea Frederick?

                  Wups, you're right, you must initialise a const object:

                  int main()
                  {
                  int const i; /* Compile ERROR */
                  }

                  The only way in which you can initialise an array when using new is to
                  default-initialise it, which is done as follows:

                  int *p = new int[3]();

                  If you stick anything inside those brackets, you've got a syntax error. If
                  your compiler allows it, then it's either broken or possibly has some sort
                  of non-Standard extension enabled.

                  Please do more snipping in future when replying.

                  --

                  Frederick Gotham

                  Comment

                  • S S

                    #39
                    Re: const char* = new char[6]


                    Frederick Gotham wrote:
                    S S posted:
                    >
                    char const *const p = new char const[6];
                    This is not compiling, saying uninitialized const in `new' of `const
                    char' How to initialize it If I give char const *const p = new char
                    const[6]("hello"); It compiles fine but if I try to print p, it does not
                    show value hello, jus blank line Any idea Frederick?
                    >
                    >
                    Wups, you're right, you must initialise a const object:
                    >
                    int main()
                    {
                    int const i; /* Compile ERROR */
                    }
                    >
                    The only way in which you can initialise an array when using new is to
                    default-initialise it, which is done as follows:
                    >
                    int *p = new int[3]();
                    Even if you do not put brackets () and write
                    int *p = new int[3];
                    then also it does the default initialisation for all 3 members of
                    array, any significance of brackets?
                    Thanks
                    >
                    If you stick anything inside those brackets, you've got a syntax error. If
                    your compiler allows it, then it's either broken or possibly has some sort
                    of non-Standard extension enabled.
                    >
                    Please do more snipping in future when replying.
                    >
                    --
                    >
                    Frederick Gotham

                    Comment

                    • S S

                      #40
                      Re: const char* = new char[6]


                      Frederick Gotham wrote:
                      S S posted:
                      >
                      char const *const p = new char const[6];
                      This is not compiling, saying uninitialized const in `new' of `const
                      char' How to initialize it If I give char const *const p = new char
                      const[6]("hello"); It compiles fine but if I try to print p, it does not
                      show value hello, jus blank line Any idea Frederick?
                      >
                      >
                      Wups, you're right, you must initialise a const object:
                      >
                      int main()
                      {
                      int const i; /* Compile ERROR */
                      }
                      >
                      The only way in which you can initialise an array when using new is to
                      default-initialise it, which is done as follows:
                      >
                      int *p = new int[3]();
                      >
                      If you stick anything inside those brackets, you've got a syntax error. If
                      your compiler allows it, then it's either broken or possibly has some sort
                      of non-Standard extension enabled.
                      You are wrong here
                      If we stick inside those brackets, the corrosponding ctor will be
                      called. Example is pasted below.
                      #include<iostre am>

                      class A {
                      public:
                      A() {a = 10;}
                      A(int b) {a = b;}
                      void dis() const { printf("%d\n",a );}
                      private:
                      int a;
                      };

                      int main()
                      {
                      A const* p = new A const[3](5); // not a default ctor
                      p->dis();
                      (p+1)->dis();
                      (p+2)->dis();
                      (*p).dis();
                      (*(p+1)).dis();
                      (*(p+2)).dis();
                      p[0].dis();
                      p[1].dis();
                      p[2].dis();
                      return 0;
                      }

                      Output will be
                      5
                      5
                      5
                      5
                      5
                      5
                      5
                      5
                      5


                      >
                      Please do more snipping in future when replying.
                      >
                      --
                      >
                      Frederick Gotham

                      Comment

                      • Frederick Gotham

                        #41
                        Re: const char* = new char[6]

                        S S posted:
                        A const* p = new A const[3](5);

                        What compiler are you using? G++ gives:

                        ISO C++ forbids initialization in array new
                        --

                        Frederick Gotham

                        Comment

                        • Frederick Gotham

                          #42
                          Re: const char* = new char[6]

                          S S posted:
                          Even if you do not put brackets () and write
                          int *p = new int[3];
                          then also it does the default initialisation for all 3 members of
                          array, any significance of brackets?

                          The Standard provides no such guarantee (well I'm 99% that it doesn't) --
                          if you want each element to be default-initialised, you'll have to use the
                          empty parentheses.

                          Testing it will do you no good, as I know of at least one implementation
                          that default-initialises new'ed memory regardless of whether you provide
                          the empty parentheses.

                          Anyhow, even if the empty parentheses were redundant, I would still put
                          them in, just as how I write:

                          int main()
                          {
                          static MyPOD arr[5] = {};
                          }

                          instead of:

                          int main()
                          {
                          static MyPOD arr[5];
                          }

                          Indeed, the chain brackets are redundant because static data always gets
                          default initialised... but nonetheless, they express clear intent.

                          --

                          Frederick Gotham

                          Comment

                          • Noah Roberts

                            #43
                            Re: const char* = new char[6]


                            S S wrote:
                            Frederick Gotham wrote:
                            int *p = new int[3]();
                            >
                            Even if you do not put brackets () and write
                            int *p = new int[3];
                            then also it does the default initialisation for all 3 members of
                            array, any significance of brackets?
                            You are mistaken. No initialization occurs if the parens are not
                            there. Not even default initialization.

                            Comment

                            Working...