Variable Sized Arrays in C

前端 未结 5 1508
予麋鹿
予麋鹿 2020-12-17 02:17

I guess my question is whether the following is valid C

int main(void) {
  int r = 3;
  int k[r];
  return 0;
}

If so, would some one care

相关标签:
5条回答
  • 2020-12-17 02:41

    It is a GCC extension that the current MSVC does not support. You can replace it in MSVC fairly easily with an _alloca (a stack allocation that requires no manual deallocation on the part of the programmer)

    yes but it is limited to 1mb

    0 讨论(0)
  • 2020-12-17 02:46

    The C99 standard added variable-length arrays, but other vendors such as GCC added them much earlier.

    0 讨论(0)
  • 2020-12-17 02:50

    I'm sorry this is not an answer, but I'd like to point out a potential problem with using variable-length arrays. Most of the code that I have come across looks like this.

    void foo(int n)
    {
        int bar[n];
        .
        .
    }
    

    There is no explicit error checking here. A large n can easily cause problems.

    0 讨论(0)
  • 2020-12-17 02:55

    It is a GCC extension that the current MSVC does not support. You can replace it in MSVC fairly easily with an _alloca (a stack allocation that requires no manual deallocation on the part of the programmer):

    #include <malloc.h>
    
    ...
    
    int *k = (int *)_alloca(sizeof(*k)*r);
    
    0 讨论(0)
  • 2020-12-17 03:00

    It is in C99. MSVC only supports C89.

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