Aviv Cohn
Aviv Cohn

Reputation: 17243

Incompatible pointer types on array initialization

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?

Upvotes: 0

Views: 175

Answers (2)

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.

Upvotes: 0

0___________
0___________

Reputation: 67835

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",
};

Upvotes: 4

Related Questions