c - struct look up table using string pointers issue -
i have written following code:
unsigned char *cptr[] = { "first", "second", "third" }; typedef struct { int a; char *lut; /* or char lut[20]*/ }grp_t; const grp_t grp_st[]= { { 0, cptr[0] }, { 1, cptr[1] }, { 2, cptr[2] } };
when try compile code got following error:
error: initializer element not constant
error: (near initialization 'grp_st[0].lut[0]')
but when replace *cptr[]
cptr[][16]
as
unsigned char cptr[][16] = { "first", "second", "third" };
i able compile code.
please can 1 explain me concept missing here.
it limitation of c.
6.7.8.4 initialization:
all expressions in initializer object has static storage duration shall constant expressions or string literals.
and 6.6.9 constant expressions:
an address constant null pointer, pointer lvalue designating object of static storage duration, or pointer function designator; shall created explicitly using unary & operator or integer constant cast pointer type, or implicitly use of expression of array or function type. array-subscript [] , member-access . , -> operators, address & , indirection * unary operators, , pointer casts may used in creation of address constant, value of object shall not accessed use of these operators.
if can change code make grp_st
not of static storage duration compiles:
#include <stdio.h> const char *cptr[] = { "first", "second", "third" }; typedef struct { int a; const char *lut; } grp_t; int main(void) { grp_t grp_st[]= { { 0, cptr[0] }, { 1, cptr[1] }, { 2, cptr[2] } }; return 0; }
in second case managed compile code because didn't access array element @ given index, pointer (in case of char cptr[][16]
, cptr[0]
gives address of first array of 16 characters , cptr[0]
decays type char *
in expression) - therefore didn't violate 6.6.9 rule.
Comments
Post a Comment