Can you define the size of an array at runtime in C

后端 未结 10 1293
走了就别回头了
走了就别回头了 2021-01-02 18:35

New to C, thanks a lot for help.

Is it possible to define an array in C without either specifying its size or initializing it.

For example, can I prompt a u

10条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 19:08

    If you're a beginner, maybe you don't want to deal with malloc and free yet. So if you're using GCC, you can allocate variable size arrays on the stack, just specifying the size as an expression.

    For example:

    #include 
    void dyn_array(const unsigned int n) {
            int array[n];
            int i;
    
            for(i=0; i

    But keep in mind that this is a non standard extension, so you shouldn't count on it if portability matters.

提交回复
热议问题