This code in CodeBlock works without errors.

typedef struct exmpl{ int index; char name[50]; int count; } result; int size; scanf("%d", &size); result data[size]; 

But in Visual Studio gives errors

error C2057: expected constant expression

error C2466: cannot allocate an array of constant size 0

error C2133: 'data': unknown size

As I understand the problem is not in the IDE but in the C standards or compilers?

  • one
    result * data = (result *) malloc (sizeof (result) * size); - Sergey
  • @Sergey, dynamically allocating memory is certainly cool, but I would understand why this can be done. - Hardc0re
  • The problem, of course, is not in the IDE, but in the compilers. Therefore, in the question you need to clarify which compiler is used in CodeBlocks and which version of Visual Studio. - zed
  • @zed, CodeBlocks - GNU GCC Compile r ---- follow C ++ 11 language language standart --------------------------- Visual Studio - 2013 - Hardc0re

2 answers 2

Where exactly do you declare your array?

If your array is declared locally, then you are trying to use Variable Length Arrays (VLA) - a property of the C language starting from version C99. The MSVC compiler does not support VLA, even though in modern MSVC support for C99 is implemented [almost] completely. Standard C11 made the VLA an optional language property, so maybe we will never see their support in MSVC.

In non-local areas, VLA cannot be advertised.

    There is no standard C arrays with dynamic selection. It was a one-time weakness, a nod to Fortranschik, which was supported by GCC, which will be used in CBlocks (by the way, IDE, which is crappy, has the most oak project configurator in this part of the universe).

    So, you want the dynamics - either malloc / realloc / free, or C ++ and STL.

    • 2
      Variable Length Arrays are standard features of the C language starting at C99. What is gcc? Another thing is that C11 made the VLA an optional feature, but that was just a curtsey to the sideways. De facto, VLAs should be supported by "full-fledged" versions of C compilers. - AnT
    • @AnT I say - minute weakness in C99, which was then thrown out of the standard. And GCC is just here in that it implements this option. - gbg
    • So whose weakness is C99 or GCC? And no, no one ever threw it out of the standard. As I said above, the goal of the optional VLA is to give more freedom to freestanding implementations (embedsmen and other users of the "truncated" C). For full hosted implementations, VLA support is de facto mandatory. - AnT
    • The @AnT Standards Committee, which first twisted the feature (C99), and then unscrewed it (C11). Trolling over, bye. - gbg