0

The following array initializer:

const char** AST_NODE_TYPE_NAMES = {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};

Makes gcc raise the following warning:

initialization of 'const char **' from incompatible pointer type 'char *'

Help me figure this out?

2
  • 4
    Pointers are not arrays. Commented May 11, 2019 at 13:34
  • 1
    ... but you've written an initializer for AST_NODE_TYPE_NAMES as if it were an array. Commented May 11, 2019 at 13:38

2 Answers 2

4

you want array of pointers

const char *AST_NODE_TYPE_NAMES[] = {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};

and this array can eventually decal to the pointer you want:

const char **foo1 = AST_NODE_TYPE_NAMES;
const char **foo = &AST_NODE_TYPE_NAMES[0];

you can also use the compound literal (which actually is the array of pointers in this case) to initialize this pointer

const char** AST_NODE_TYPE_NAMES =(const char *[]) {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};
Sign up to request clarification or add additional context in comments.

Comments

0

A pointer is not an aggregate but a scalar, and it expects one value to initialize it. In C it is also permissible to wrap the scalar initializer in { }!

Thus:

const char** AST_NODE_TYPE_NAMES = {
     "AST_NODE_CONSTANT",
     "AST_NODE_BINARY",
     "AST_NODE_UNARY",
     "AST_NODE_VARIABLE",
     "AST_NODE_ASSIGNMENT",
     "AST_NODE_STATEMENTS",
};

tries to initialize one pointer to pointer to const char with the address of the first character of string literal "AST_NODE_CONSTANT", but that does not have type const char ** but just char *. In addition to that, there are 5 excess initializers, namely the following strings.


What you of course want to do is to initialize an array, as P__J__ already showed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.