简体   繁体   中英

Initialized Variable Length Array Working Variably (Between Computers)

I have some code that initializes arrays, specifically C-strings, using variables. For example...

int len = getLength();
char cstr[len+1] = {'\0'};

This compiles and runs flawlessly in my code. However, when one of my co-workers runs the same code, he gets the compiler error...

Variable-sized object may not be initialized

We're both using Ubuntu and GCC/G++. We've compared compiler flags, and we're both using --std=c++11 . All the rest of the flags are also the same ( -Wall , -Wextra and -g ).

Why is this code only working on my computer, and not his? How can I get it working?

This is a case of different compiler versions . When we both ran g++ --version in our terminals, we found he was running 4.8 , while I was running 4.9 .

GCC has long supported C99 variable-length arrays (VLAs), where a variable is declared, but not given an initialization list. Thus, my co-worker could resolve the errors by removing {'\\0'); from each initialization (which also broke the code in this case.)

However, in bygone days, GCC has not supported C++1y VLAs, which is what I had in the example in the question. They just added support for those in GCC 4.9 (see the Changelog ).

Ubuntu 14.04 (what my co-worker has) ships with GCC 4.8, while Ubuntu 15.04 (what I have) ships with GCC 4.9. Thus, we had to get onto the same compiler version, namely GCC 4.9. (Instructions for doing that are on this question .)

If you're running into this issue on Windows, there are options there as well. As of writing, MSYS2 currently offers GCC 5.2 by default, and TDM-GCC offers GCC 5.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM