George Hilliard
George Hilliard

Reputation: 15952

How to refer to variable-length structures

The below code refuses to compile in SDCC, because of my use of flexible array members (the "This line"s).

/** header of string list */
typedef struct {
    int nCount;
    int nMemUsed;
    int nMemAvail;
} STRLIST_HEADER;

/** string list entry data type */
typedef struct {
    int nLen;
    char str[];                    // This line
} STRLIST_ENTRY;

/** string list data type */
typedef struct {
    STRLIST_HEADER header;
    STRLIST_ENTRY entry[];         // This line
} STRLIST;

int main()
{
    return 0;
}

However, the data I have to access is already set up this way (I'm accessing existing memory via pointers, not smashing the stack), and using a struct pointer makes for very clean code. Unfortunately SDCC does not like this. What is an alternative way I could refer to the memory structure in my code that will compile cleanly?

Upvotes: 0

Views: 564

Answers (2)

Carah
Carah

Reputation: 1

typedef struct {
    int nLen;
    char *str;                    
} STRLIST_ENTRY;

I would do it this way and malloc the array when ready to use it. Is there any particular reason you are using all caps to define a struct name? Usually these are lowercase in most coding standards.

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281505

The usual way is to give the array member a size:

typedef struct {
    int nLen;
    char str[1];
} STRLIST_ENTRY;

That keeps the compiler happy.

Edit: Can you use the --std-c99 or --std-sdcc99 switches to make SDCC understand your original code?

Upvotes: 1

Related Questions