robert
robert

Reputation: 4867

pointer to anonymous struct array in c

So I have an array declared like this (it's not my code, and I will not modify it):

static const struct {
    int gsmesc;
    int latin1;
    int utf8_int;
    char *utf8;
    ...

} gsm_escapes[] = {
    {  10, 12 , 0x0C, "\x0C" },
    {  20, '^', 0x5E, "\x5E" }, 
    ...
};

Notice that the struct itself is untagged.

I want to iterate this array with a pointer (rather than an array subscript), and the best I could come up with is this, which compiles without any warnings:

typeof(*gsm_escapes) *esc;
...

esc = gsm_escapes;
while (esc++->gsmesc != -1) {

    esc = gsm_escapes;
    while (esc->gsmesc != -1) {

Is there a "proper" way to declare this pointer type since this approach seems uncharacteristically inelegant?

What is this type of data structure even called? I've been googling for a good while now and haven't come up with any primers that cover it.

Upvotes: 0

Views: 1032

Answers (1)

dbush
dbush

Reputation: 225787

Using typeof is the only direct way to do this since the struct doesn't have a tag. It's also non-standard, so not all compilers may support it.

Your choices are:

  • Leave it as it is
  • Use array notation instead of pointer notation:

    int i=0;
    while (gsm_escapes[i++]->gsmesc != -1) {
    
        i=0;
        while (gsm_escapes[i]->gsmesc != -1) {
    
  • Create a typedef for the struct using typeof. That way the typeof expression only appears once:

    typedef typeof(*gsm_escapes) struct_gsm_escapes;
    ...
    struct_gsm_escapes *esc;
    

Upvotes: 2

Related Questions