Strange C code - dynamic arrays?

后端 未结 4 499
说谎
说谎 2021-01-23 04:25

I have a bit of code copied from an unknown source:

 int Len=0;
 printf(\"Please input the length of vector\");
 scanf(\"%d\",&Len);
 float x[Len],y[Len],si         


        
相关标签:
4条回答
  • 2021-01-23 04:36

    This is called a Variable Length Array (VLA) and is a C99 feature.

    If your compiler does not recognise it on it's own then try switching C standards

    Try:

    --std=c99
    -std=c99
    --std=gnu99
    -std=gnu99
    

    The manual page of your compiler will be able to tell you the exact flag.

    0 讨论(0)
  • 2021-01-23 04:52

    Now normally I believe that arrays cannot be initialized during runtime with a variable.

    That has been true before C99 standard. It is also illegal in C++ (although some compilers, such as gcc, offer this as an extension).

    Is there a C variant where this is legal?

    Any C99 compiler will do.

    I am also seeing arrays indexed from 1 rather than 0

    This is OK as well, as long as you are fine allocating an extra element, and not using element at index zero.

    Note: since accessing an element past the end of an array is undefined behavior, an invalid program may appear to work and produce the desired result in your test runs. If you suspect that some array indexes may be off by one, consider running your program under a memory profiler, such as valgrind, to see if the program has hidden errors related to invalid memory access.

    0 讨论(0)
  • 2021-01-23 04:57

    In C99 this is valid and called a VLA-Array.

    0 讨论(0)
  • 2021-01-23 04:58

    This was a feature introduced in C99 and are called VLAs(Variable Length Arrays). These arrays are also indexed starting from 0 not 1 and ending at length-1(Len-1 in your case) just like a normal array.

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