c语言中近年出了重要新规范,C99,C11,其中C99提出了变长数组VLA,然后在C11中变成一个非必须实现的特性。

由于Visual Studio/VC不支持变成数组VLA,于是有了这篇文章。

malloc版本代码

/* vla1.c -- 使用malloc函数模拟动态数组*/
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    //模拟变长数组VLA,申明一个int[4][3]的二维数组
    int (*ar)[3] = malloc( 4 * 3 * sizeof(int));
    ar[0][0] = 12;
    printf("**ar = %d", **ar);
    free(ar);
    
    return 0;
}

 

第一个版本是笔者在看完《C Primer Plus》第六版本,第10章《数组和指针》和指针后写出的代码,

此版本的特点是要使用堆内存,用完要是否,否则系统无法回收。

 

后来向大佬们请教,得知可以用alloca函数,据了解通过gcc反编译变长数组,内部函数使用了alloac等价代码,

alloca申请的内存在栈上面,用完自动释放,不会浪费堆内存,也不需要手动释放。跨平台,建议在x86,x86_64

等平台使用。alloac申请的内存也不要太大,栈会爆。

 关于alloca的函数说明:

The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that
called alloca() returns to its caller.

第二版

/*alloca1.c -- 使用alloca函数模拟动态数组*/
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    //模拟变长数组VLA,申明一个int[4][3]的二维数组
#ifdef _MSC_VER
    int (*ar)[3] = _alloca( 4 * 3 * sizeof (int));
#else
    int (*ar)[3] = alloca( 4 * 3 * sizeof(int));
#endif
    ar[0][0] = 12;
    printf("**ar = %d", **ar);
    
    return 0;
}

 

 

 

鸣谢网友:靓仔敬业栋(微信群:嵌入式Linux,c,c++(1)群),oo(QQ群:Drogon交流/1137909452)

posted on 2021-09-27 11:18  你不知道的浪漫  阅读(429)  评论(0编辑  收藏  举报