美文网首页
使用指针和molloc函数来实现变长数组(VLA)

使用指针和molloc函数来实现变长数组(VLA)

作者: JingWenxing | 来源:发表于2019-02-25 23:33 被阅读0次

    实现思路:

    1、输入创建指针大小 SIZE
    2、使用 sizeof 函数得出需要的空间大小。例:输入 10sizeof(int) * SIZE 得出40。
    3、使用 malloc 函数动态分配内存空间。(注:一般的时候,malloc 函数与 free 函数连用)
    4、用 for 循环输入每一个数据。
    5、用 free 函数释放内存空间。

    实现代码:

    #include <cstdio>
    #include <cstdlib>
    void usePtoImplementVLA(int SIZE)
    {
        scanf("%d", &SIZE);
        int *pVLA = (int *)malloc(sizeof(int) * SIZE);
        
        for (int i = 0; i < SIZE; i++)
            scanf("%d", &pVLA[i]);
        
        free(pVLA);
    }
    

    参考资料:

    来源:Reference

    链接:cplusplus-malloc

    ——————————

    来源:百度百科

    链接:malloc函数

    ——————————

    来源:Cppreference

    链接:sizeof 运算符

    ——————————

    相关文章

      网友评论

          本文标题:使用指针和molloc函数来实现变长数组(VLA)

          本文链接:https://www.haomeiwen.com/subject/ynxoyqtx.html