Strange C code - dynamic arrays?

后端 未结 4 513
说谎
说谎 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: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.

提交回复
热议问题