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;
Xiè Jìléi
  • 12,877
  • 15
  • 73
  • 101

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,130
  • 1
  • 24
  • 41
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,342
  • 20
  • 35