convertion form char** to const char** error

Discussion in 'C++' started by mihai, Apr 15, 2008.

  1. mihai

    mihai Guest

    Hi,

    I have a question regarding the conversion (in c or c++) from char**
    to const char**.

    The fallowing code refuses :) to compile with g++ (and others):

    char **p;
    const char **q = static_cast<const char**>(p);

    or, exact the same situation:

    void f(const char **p) {}
    int main() {
    f(p);
    return 0;
    }

    And I don't understand why. It should work because is a conversion for
    a non const pointer to a const pointer.

    Thank you,
    Mihai.
    mihai, Apr 15, 2008
    #1
    1. Advertising

  2. mihai wrote:
    > char **p;
    > const char **q = static_cast<const char**>(p);


    Rather ironically const_cast will work. (It's ironic because
    const_cast is usually used to *remove* constness, not to add it.)
    Juha Nieminen, Apr 15, 2008
    #2
    1. Advertising

  3. Juha Nieminen, Apr 15, 2008
    #3
  4. mihai

    James Kanze Guest

    On 15 avr, 11:53, mihai <> wrote:

    > I have a question regarding the conversion (in c or c++) from
    > char** to const char**.


    > The fallowing code refuses :) to compile with g++ (and others):


    > char **p;
    > const char **q = static_cast<const char**>(p);


    > or, exact the same situation:


    > void f(const char **p) {}
    > int main() {
    > f(p);
    > return 0;
    > }


    > And I don't understand why. It should work because is a
    > conversion for a non const pointer to a const pointer.


    No it's not. It's a conversion between two different types of
    non-const pointers. Allowing it would break const:

    char* p ;
    char** pp = &p ;
    char const** pcp = pp ;
    char const* pc = "doh!" ;
    *pcp = pc ;
    *p = '\0' ;

    Thus, it's forbidden.

    --
    James Kanze (GABI Software) email:
    Conseils en informatique orientée objet/
    Beratung in objektorientierter Datenverarbeitung
    9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
    James Kanze, Apr 15, 2008
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Thomas Matthews
    Replies:
    5
    Views:
    2,404
    tom_usenet
    Aug 2, 2004
  2. Replies:
    24
    Views:
    827
    Netocrat
    Oct 30, 2005
  3. lovecreatesbeauty
    Replies:
    1
    Views:
    1,034
    Ian Collins
    May 9, 2006
  4. Javier
    Replies:
    2
    Views:
    558
    James Kanze
    Sep 4, 2007
  5. HackerisNewKnight
    Replies:
    4
    Views:
    575
    HackerisNewKnight
    Sep 7, 2007
Loading...

Share This Page