简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM