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

2019-02-25  本文已影响0人  JingWenxing

实现思路:

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 运算符

——————————

上一篇下一篇

猜你喜欢

热点阅读