0

Compile this program:

#include <stdio.h>

void main() {
    char *s = "helo";
    char **sp = &s;
    const char **csp = sp;
    const char *cs = *csp;
    printf("%s\n", cs);
}

get the warning:

cc.c: In function ‘main’:
cc.c:6:24: warning: initialization from incompatible pointer type [enabled by default]
     const char **csp = sp;
Lenik
  • 13,946
  • 17
  • 75
  • 103
  • 3
    http://www.parashift.com/c++-faq-lite/constptrptr-conversion.html <-- I know there is a duplicate SO answer somewhere, but this is the answer. – Billy ONeal Nov 13 '13 at 05:50
  • Not really a duplicate, that question is about C++ and the example is fine in C++ but produces a warning in C. https://godbolt.org/z/cdMvW54s5 – Giovanni Cerretani Jul 04 '23 at 12:49

2 Answers2

1

char **sp

sp is a pointer to pointer to char and sp, *sp, and **sp are all mutable

const char **csp

csp is a pointer to pointer to const char and, csp and *csp are mutable but **csp is const

Now lets see why const char** csp = sp is not safe.

const char Imconst = 'A';
char* ImMutable;
const char** ImConstPtr = &ImMutable;  // This is illegal but if it is allowed
*ImConstPtr  = &Imconst;
*ImMutable = '1'; // We are trying to assign to "Imconst"

Hope this clears the doubt.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

The warning is because char ** and const char ** are not equivalent. To be correct, you could fix the prototype (callee), or fix the caller (const char *).

find fantastic article at http://c-faq.com/ansi/constmismatch.html

SD.
  • 1,432
  • 22
  • 38