我有一个结构:
typedef struct stock {
const char* key1p2; // stock code
const char* key2p2; // short desc
const char* desc1; // description
const char* prod_grp; // product group
const char dp_inqty; // decimal places in quantity
const long salprc_u; // VAT excl price
const long salprc_e; // VAT includive price
const long b_each; // quantity in stock
const long b_alloc; // allocated qty
const char* smsgr_id; // subgroup
const char** barcodes; // barcodes
} stock_t;
我想在每个股票结构的一行代码中初始化这个结构的实例数组。
我试过了:
stock_t data_stock[] = {
{ "0001", "Soup", "Tomato Soup", "71", 0, 100, 120, 10, 0, "", {"12345", "23456", NULL} },
{ "0002", "Melon", "Melon and Ham", "71", 0, 200, 240, 10, 0, "", {"34567", "45678", NULL} },
...
{ NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL }
};
但它失败了:
data.c:26:74: warning: incompatible pointer types initializing 'const char **' with an expression of type 'char [6]'
[-Wincompatible-pointer-types]
{ "0001", "Soup", "Tomato Soup", "71", 0, 100, 120, 10, 0, "", {"12345", "23456", NULL} },
^~~~~~~
有问题的是条形码字段,因为它是 char**。
(那是铿锵声,但 GCC 报告了类似的错误,但帮助不大。)
就好像编译器忽略了“12345”之前的大括号。
我可以使用以下方法解决该问题:
const char *barcodes0001[] = {"12345", "23456", NULL};
stock_t data_stock[] = {
{ "0001", "Soup", "Tomato Soup", "71", 0, 100, 120, 10, 0, "", barcodes0001 },
这个问题的原因是 char [] 和 char *之间的不同,还是有更微妙的东西。(也许您可以初始化结构数组,但不能初始化数组结构。)