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

微笑、不失礼 提交于 2020-08-19 00:13:52

问题


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 *));

I have this code segment, and I get following error:

error: variable-sized object may not be initialized|

I figured out the problem is causing from the variable 'integer' as when I delete it, I don't face this error. But I can't understand why I am seeing it because I already initialized 'integer' variable. Also, I already initialized "myStruct" structure and initializing str1 right here.

Can someone help me?


回答1:


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.)



来源:https://stackoverflow.com/questions/20818822/error-variable-sized-object-may-not-be-initialized-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!