开发者

Enabling VLAs (variable length arrays) in MS Visual C++?

开发者 https://www.devze.com 2023-02-15 15:17 出处:网络
How can I enable the use of VLAs, variable length arrays as defined in C99, in MS Visual C++ or that is not possible at all?

How can I enable the use of VLAs, variable length arrays as defined in C99, in MS Visual C++ or that is not possible at all?

Yes I know that the C++ standard is based on C89 and that VLAs are not available in C89 standard and thus aren't availa开发者_JS百科ble in C++, but MSVC++ is supposed to be a C compiler also, a behavior that can be switched on using the /TC compiler parameter (Compile as C Code (/TC)). But doing so does not seem to enable VLAs and the compiling process fails with the same errors when building as C++ (Compile as C++ Code (/TP)). Maybe MSVC++ C compiler is C89 compliant only or I am missing something (some special construct or pragma/define)?

Code sample:

#include <stdlib.h>

int main(int argc, char **argv)
{
  char pc[argc+5];

  /* do something useful with pc */

  return EXIT_SUCCESS;
}

Compile errors:

error C2057: expected constant expression

error C2466: cannot allocate an array of constant size 0

error C2133: 'pc' : unknown size


MSVC is not a C99 compiler, and does not support variable length arrays.

At https://learn.microsoft.com/en-us/cpp/c-language/ansi-conformance MSVC is documented as conforming to C90.


VLA's are much neater to write but you can get similar behaviour using alloca() when the dynamic memory allocation of std::vector is prohibitive.

http://msdn.microsoft.com/en-us/library/x9sx5da1.aspx

Using alloca() in your example would give:

#include <stdlib.h>
#include <alloca.h>

int main(int argc, char **argv)
{
  char* pc = (char*) alloca(sizeof(char) * (argc+5));

  /* do something useful with pc */

  return EXIT_SUCCESS;
}


I met same problem, this is not possible in MS Visual C++ 2015, instead you can use vector to do almost the same, only difference is neglectable overhead of heap resource manage routine(new/delete).

Although VLAs is convenient, but to allocate non-deterministic amount of memory from the stack at risk of stack overflow is generally not a good idea.


MSVC 2015 does not support C99. Use this logic using dynamic memory allocation instead..

#include <stdlib.h>

int main(int argc, char** argv)
{
    char* pc = (char*)malloc((argc + 5) * sizeof(char));

    /* do something useful with pc */
    
    free(pc);
    return EXIT_SUCCESS;
}


To create a variable length array using c++, using your example, you would do something like the following:

size_t size = argc + 5;
vector<char> pc(size);

If you wanted to convert it over to std:string:

string buffer(pc.begin(), pc.end());
0

精彩评论

暂无评论...
验证码 换一张
取 消