变长数组

138 阅读1分钟
#include<stdio.h>
#include <malloc.h>
//在c99标准中,支持变长数组
    int length = 10;
    int arr7[length];
    int arr8[length+8];


    //方式2:使用malloc()函数,动态分配内存,创建一个指定长度的数组
    int *arr9 = (int*)malloc(length*sizeof(int));    //在堆空间开辟的数组空间
    arr9[0] = 10;
    arr9[1] = 20;
    printf("%d\n",arr9[1]);

   //注意:使用完动态创建的数组后,一定要回收此数组的内存空间,否则,就存在内存泄露
    free(arr9);
    return 0;
}

执行结果

20

Process finished with exit code 0