arrays - How to initialise a complex C struct in one line? -
i have structure:
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;
and want initialise arrays of instances of structure, in 1 line of code per stock struct.
i have tried:
stock_t data_stock[] = { { "0001", "soup", "tomato soup", "71", 0, 100, 120, 10, 0, "", {"12345", "23456", null} }, { "0002", "melon", "melon , ham", "71", 0, 200, 240, 10, 0, "", {"34567", "45678", null} }, ... { null, null, null, null, 0, 0, 0, 0, 0, null, null } };
but fails with:
data.c:26:74: warning: incompatible pointer types initializing 'const char **' expression of type 'char [6]' [-wincompatible-pointer-types] { "0001", "soup", "tomato soup", "71", 0, 100, 120, 10, 0, "", {"12345", "23456", null} }, ^~~~~~~
it barcode field problematic, char**.
(that clang, gcc reports similar error, less helpfully.)
it's if compiler has ignored curly brace before "12345".
i can work around problem using:
const char *barcodes0001[] = {"12345", "23456", null}; stock_t data_stock[] = { { "0001", "soup", "tomato soup", "71", 0, 100, 120, 10, 0, "", barcodes0001 },
is cause of problem different between char [] , char *, or there more subtle. (perhaps can initialise arrays of structs, not structs of arrays.)
to avoid have declare named dummy variable can use compound literal
stock_t data_stock[] = { { "0001", "soup", "tomato soup", "71", 0, 100, 120, 10, 0, "", (const char*[]){"12345", "23456", null} }, { "0002", "melon", "melon , ham", "71", 0, 200, 240, 10, 0, "", (const char*[]){"34567", "45678", null} }, ... { null, null, null, null, 0, 0, 0, 0, 0, null, null } };
this way define local temporary variable syntax of (type){ initializers }
available since c99 (and clang , gcc have them).
edit: lifetime of these compound literals same variable data_stock
suppose ok. in case think should mark of fields const
, e.g const char*const key1p2;
also easier read if you'd use designated initializers
{ .keyp1 = "0001", ... }
Comments
Post a Comment