Why an array of structs containing a pointer member has to be const?

Viewed 46

This question actually arose when I was using the OptionEntry struct which happens to have a void* field. So the example below is not too hypothetical.

struct Item {
    public string name;
    public void* data;
}

class Main: Object
{
    static int book_data;
    static int pen_data;
    
    const Item[] items = {
        { "book", ref book_data },
        { "pen",  ref pen_data }
    };
    
    public static void main(){
    }
}

This examples compiles OK. But when you make the items array a non-const variable:

   ...
    Item[] items = {
        { "book", ref book_data },
        { "pen",  ref pen_data }
    };
   ...

it fails to compile with the error: Invalid type for member `data'. And aside from that if you change the pointer member of the Item struct to a non-pointer member, the code compiles without error:

struct Item {
    public string name;
    public int data;
}
   ...
    Item[] items = {
        { "book", book_data },
        { "pen",  pen_data }
    };

Can somebody explain what's happening here. (I read the note about struct arrays on Vala FAQ.)

0 Answers
Related