2

Why this code give me a warning says: passing argument 1 of "test" from incompatible pointer type? I know it's about the const before char **, but why?

void test(const int ** a)
{
}
int main()
{
    int a=0;
    int *b=&a;
    int **c=&b;
    test(c);
    return 0;
}
ycshao
  • 1,768
  • 4
  • 18
  • 32
  • possible duplicate of [Why can't I convert 'char**' to a 'const char* const*' in C?](http://stackoverflow.com/questions/78125/why-cant-i-convert-char-to-a-const-char-const-in-c) – Adam Rosenfield Sep 08 '11 at 03:21

3 Answers3

5

You can't assign an int ** to a const int **, because if you did so, the latter pointer would allow you to give an int * variable the address of a const int object:

const int myconst = 10;
int *intptr;
const int **x = &intptr;    /* This is the implicit conversion that isn't allowed */
*x = &myconst;              /* Allowed because both *x and &myconst are const int * ... */
/* ... but now intptr points at myconst, and you could try to modify myconst through it */
caf
  • 233,326
  • 40
  • 323
  • 462
2
const int ** 

is a pointer to a pointer to a const int, but you are passing a pointer to a pointer to an int

I think you may want to declare test with int ** const, which says that the pointer is const and not the value.

NOTE: and I think this should be put in every question regarding pointers in C: cdecl.org is a pretty nice way of giving a human-readable expression

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
0

The second answer to this question might be helpful:

Why can't I convert 'char**' to a 'const char* const*' in C?

Unfortunately the accepted answer is not very good and does nothing to explain the reason.

Community
  • 1
  • 1
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Answer display order is randomized now, and the owner can change which answer is accepted, so you might want to clarify which answers you refer to. Also I would say that question is not particularly relevant anyway: this question asks about the case of converting `int **` to `const int **` (note the lack of second `const`) – M.M Nov 21 '17 at 06:32