Initialize sized, static string lists in C -
Initialize sized, static string lists in C -
i want create string lists discoverable size , not sure if have right method/syntax. here attempt:
typedef struct { unsigned int size; char** list; } strlist; static strlist listmediatype = { .size = 7, .list = { "book", "map", "booklet", "pamphlet", "magazine", "report", "journal" }, };
is right approach? note not want hardcode size construction because want utilize same type define many different lists. example, imagine next function:
void printlist( strlist* plist ){ for( int x = 0; x < plist->size; x++ ) printf( "%s\n", plist->list ); }
it can done c99 compound-literals , slight change: http://coliru.stacked-crooked.com/a/4497d2645ad21b74
typedef struct strlist{ unsigned int size; char** list; } strlist; static strlist listmediatype = { .size = 7, .list = (char*[]){ "book", "map", "booklet", "pamphlet", "magazine", "report", "journal" }, };
alternative c90 (thus without compound-literals , designated initializers): http://coliru.stacked-crooked.com/a/5cc95d25afc18c91
static char* list[] = { "book", "map", "booklet", "pamphlet", "magazine", "report", "journal" }; static strlist listmediatype = { sizeof list / sizeof *list, // used sizeof avoid manually typing lists length list, };
as aside, array sentinel-null
far simpler counted array. not need new type.
static char* list[] = { "book", "map", "booklet", "pamphlet", "magazine", "report", "journal", 0 }; void printlist(char** plist){ while(*plist) printf( "%s\n", *plist++); }
c string struct static initialization
Comments
Post a Comment