error: variable-sized object may not be initialized| (C language)

后端 未结 1 631
抹茶落季
抹茶落季 2021-01-03 17:12

I am a beginner of programming so I am not familiar to errors yet.

int integer=1;
struct myStruct **str1[integer] = malloc(sizeof(struct myStruct *));


        
相关标签:
1条回答
  • 2021-01-03 17:38

    The problem is that because integer is not a compile-time integer constant (and it won't be even if you define it as const int integer = 1;), the array you declare using it is a VLA — variable length array. And you cannot define initializers for VLAs, even when you know the size at compile time.

    The C standard says:

    ISO/IEC 9899:2011 §6.7.9 Initialization

    ¶3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

    That's a constraint; there is no wriggle room. Though shalt not initialize a VLA.


    Further scrutiny

    In this context, I'd probably use 1 (or even nothing) as the array dimension:

    int integer=1;
    struct myStruct **str1[1] = { malloc(sizeof(struct myStruct *)) };
    

    Or:

    int integer=1;
    struct myStruct **str1[] = { malloc(sizeof(struct myStruct *)) };
    

    Note the use of initializer { ... } braces which are necessary for initializing an array.

    However, it is not remotely clear what you are trying to do here; you have 3 levels of pointer on the LHS and only 1 in the sizeof on the RHS. While sizeof(struct myStruct *) == sizeof(struct myStruct **), it is not clear what you are up to. My suspicion is you really want:

    size_t str_size = 1;
    struct myStruct **str1 = malloc(sizeof(*str_size) * str_size);
    

    This allocates space for one struct myStruct pointer, but the allocation can grow later so that you can have many such pointers in an array, the size of which is described by the str_size variable.

    This is not initializing an array (or structure), so the { ... } must be absent.

    I'll also note that I've kept the str prefix out of deference to your code, but most people expect str to refer to 'string', not 'structure' (think strlen() etc). So you should probably not use str as the prefix. (And, in my view, adult programmers do not use 'my' as a prefix either. However, not everyone agrees with me — witness 'MySQL' and 'My Documents', though in the latter case, one might argue that we're being treated as children anyway.)

    0 讨论(0)
提交回复
热议问题